LeetCode 3244. 新增道路查询后的最短距离 II(区间并查集)
原题链接
困难
作者:
autumn_0
,
2024-11-20 20:27:39
,
所有人可见
,
阅读 1
class UnionFind {
public int[] p;
public UnionFind(int size)
{
p = new int[size];
for(int i = 0; i < size; i ++ )
p[i] = i;
}
public int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
}
class Solution {
public int[] shortestDistanceAfterQueries(int n, int[][] queries) {
UnionFind uf = new UnionFind(n - 1);
int[] ans = new int[queries.length];
int cnt = n - 1;
for(int qi = 0; qi < queries.length; qi ++ )
{
int l = queries[qi][0];
int r = queries[qi][1] - 1;
int pr = uf.find(r);
for(int i = uf.find(l); i < r; i = uf.find(i + 1))
{
uf.p[i] = pr;
cnt -- ;
}
ans[qi] = cnt;
}
return ans;
}
}