C - No Collision Moves Editorial by evima
First, if there exists a pair of people \((i,j)\) such that \(S_i < S_j\) and \(T_i > T_j\), the answer is No. This is because when one of persons \(i,j\) moves first, they will inevitably fight with the other. This condition can be checked by sorting \((S_1,T_1),(S_2,T_2),\ldots,(S_N,T_N)\) in ascending order of \(S\) and checking if the values of \(T\) are also in ascending order.
From now on, consider the case where no such pair of people \((i,j)\) exists.
Let \(X\) be the set of people \(i\) satisfying \(S_i < T_i\), and \(Y\) be the set of people \(i\) satisfying \(S_i > T_i\). Then, from the above condition, for \(i \in X, j \in Y\), we have \([S_i , T_i] \cap [T_j , S_j] = \emptyset\). Therefore, we can consider \(X\) and \(Y\) as independent problems.
Considering only people belonging to \(X\), from the condition, we can achieve movement without fights by moving people in descending order of \(S\) values. Similarly, for \(Y\), we should move people in ascending order of \(S\) values.
By implementing this appropriately, we can solve this problem. The time complexity is \(O(N \log N)\).
Implementation Example (Python3)
n = int(input())
ch = [() for _ in range(n)]
c1 = []
c2 = []
for i in range(n):
s, t = map(int, input().split())
ch[i] = (s, t)
if s < t:
c1.append((s, i))
else:
c2.append((s, i))
ch.sort()
for i in range(n - 1):
if ch[i][1] > ch[i + 1][1]:
print("No")
exit()
c1.sort(reverse=True)
c2.sort()
ans = []
for s, i in c1:
ans.append(i + 1)
for s, i in c2:
ans.append(i + 1)
print("Yes")
print(*ans)
posted:
last update: