题解:AT_abc411_f [ABC411F] Contraction

· · 题解

思路

可以发现在任何询问时,棋⼦ u_{x_i},v_{x_i} 要么是相邻的点,要么被缩在一个点中,又可以发现两个棋子之间都有相连。因此收缩边时可以使用并查集维护棋子所在的点。

然后需要处理收缩边时出现的重边和自环的情况。就可以使用 set 维护每个点的连接出去的边,并用启发式合 并优化收缩边操作,由边数少的点合并进边数多的点。

时间复杂度

并查集总时间复杂度 O(N\log N)。

启发式合并总时间复杂度 O(M\log M\log N)。

总时间复杂度 O(N\log N + M\log M \log N)。

代码

#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;
}