题解:AT_abc411_f [ABC411F] Contraction
思路
可以发现在任何询问时,棋⼦
然后需要处理收缩边时出现的重边和自环的情况。就可以使用 set 维护每个点的连接出去的边,并用启发式合
并优化收缩边操作,由边数少的点合并进边数多的点。
时间复杂度
并查集总时间复杂度
启发式合并总时间复杂度
总时间复杂度
代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int ll
const int N = 3e5 + 10;
int n, m, q, ans, u[N], v[N], fa[N];
set<int> s[N];
int Find(int x){
return fa[x] == x ? x : fa[x] = Find(fa[x]);
}
void M(int x, int y){
if(s[x].size() < s[y].size()){
swap(x, y);
}
fa[y] = x;
for(int i : s[y]){
s[i].erase(y);
ans--;
if(i != x && !s[x].count(i)){
ans++;
s[x].insert(i);
s[i].insert(x);
}
}
s[y].clear();
s[x].erase(y);
}
signed main(){
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> ans;
for(int i = 1; i <= ans; i++){
cin >> u[i] >> v[i];
s[u[i]].insert(v[i]);
s[v[i]].insert(u[i]);
}
iota(fa + 1, fa + n + 1, 1);
cin >> q;
while(q--){
int x;
cin >> x;
int xx = Find(u[x]), yy = Find(v[x]);
if(xx != yy){
M(xx, yy);
}
cout << ans << '\n';
}
return 0;
}