from ACL1
ACL1A
A - Reachable Towns
Thoughts.
? No, [DSU] because the relationship is symmetrical.Sort in advance
Take one leading (argmin x)
Groups are determined by comparing y
Take one lead from the rest.
The same thing over and over again.
Can we ignore those already in the group? →Can't.
There is a vertex that joins the group later in these patterns.
→ This is no good because the number of comparisons is on the order of squared.
Process of occurrence of misunderstandings
succession
In the process of this operation, it is found that only the component with the smallest y-coordinate in each linkage should be kept, so the number of merge operations can be reduced to O(N) by using set and stack to manage them.
Because stretching many edges reduces the number of vertices to be seen in the future, the stretching operation is only performed amortized O(N) times, and the rest can be solved by implementing this properly.
Official Explanation O(N) Solution
def solve(N, XS, YS):
size = [0] * N
x2y = [0] * N
x2i = [0] * N
for i in range(N):
x2y[XS[i]] = YS[i]
x2i[XS[i]] = i
ymax = N - 1
x = 0
while x < N:
start = x
y0 = x2y[x]
k = ymax - y0
ymin = y0
while k or ymax - ymin > x - start:
x += 1
y = x2y[x]
if y0 < y:
k -= 1
ymin = min(ymin, y)
end = x + 1
s = end - start
for x in range(start, end):
size[x2i[x]] = s
x += 1
ymax = ymin - 1
return size
This page is auto-translated from /nishio/ACL1A using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.