This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#define ll long long
#define ldb long double
#define endl '\n'
#define For(i,l,r) for(int i=l;i<=r;i++)
#define ForD(i,r,l) for(int i=r;i>=l;i--)
#define REP(i,l,r) For(i,l,r-1)
#define PER(i,r,l) ForD(i,r-1,l)
#define ff first
#define ss second
#define pb push_back
#define all(x) x.begin(),x.end()
#define All(x,n) x+1,x+1+n
#define Alll(x,n) x,x+n
#define sz(x) (signed)x.size()
#define unq(x) x.resize(unique(all(x))-x.begin())
#define mpa make_pair
#ifdef NCGM
#include"debug.h"
#else
#define debug(...) "fr";
#endif
using namespace std;
const int N=1e5+3;
int n,m,f[N],f1[N],mmb[N];
ll ans=0;
map<int,int> mp[N],mp1[N];
set<int> st[N];
vector<int> ahu,ahu1;
int find_set(int u) {
return (f[u]<0?u:f[u]=find_set(f[u]));
}
int find_set1(int u) {
return (f1[u]<0?u:f1[u]=find_set1(f1[u]));
}
void unite(int u,int v) {
int a=find_set(u),b=find_set(v);
if (a==b) return;
int a1=find_set1(u),b1=find_set1(v);
ans+=1LL*f[a]*(sz(st[a1])-1);
ans+=1LL*f[b]*(sz(st[b1])-1);
if (sz(st[a1])<sz(st[b1])) swap(a1,b1);
if (sz(mp[a])+sz(mp1[a])<sz(mp[b])+sz(mp1[b])) swap(a,b);
ahu.clear();
ahu1.clear();
for(auto el: mp[b]) {
ahu.pb(el.ff);
if (mp[find_set(el.ff)].count(a) || mp[find_set(el.ff)].count(b)) ahu1.pb(el.ff);
}
for(auto el: mp1[b])
if (mp1[el.ff].count(a) || mp1[el.ff].count(b)) ahu1.pb(el.ff);
for(auto el: mp1[b1]) {
mp[el.ff][a]=mp[el.ff][b];
mp[el.ff].erase(mp[el.ff].find(b));
}
for(auto el: ahu) {
mp1[el][a]=mp1[el][b];
mp1[el].erase(mp1[el].find(b));
}
for(auto el: st[b1]) st[a1].insert(el);
st[b1].clear();
for(auto el: mp[b]) mp[a][el.ff]+=el.ss;
mp[b].clear();
for(auto el: mp1[b]) mp1[a][el.ff]+=el.ss;
mp1[b].clear();
//if (u==1 && v==2) debug(mmb[a],find_set1(3));
f[a]+=f[b];
f1[a1]+=f1[b1];
f[b]=a;
f1[b1]=a1;
ans-=1LL*f[a]*(sz(st[find_set1(a)])-1);
for(auto el: ahu1) {
if (find_set(el)==find_set(a)) continue;
unite(el,a);
}
}
void add_edge(int u,int v) {
if (find_set(u)==find_set(v) || mp[find_set(v)].count(find_set(u))) return;
ans-=f[find_set(v)];
mp[find_set(v)][find_set(u)]++;
mp1[find_set(u)][find_set(v)]++;
st[find_set1(v)].insert(u);
if (mp[find_set(u)].count(find_set(v))) unite(u,v);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
For(i,1,n) f[i]=f1[i]=-1;
For(i,1,n) st[i].insert(i);
For(i,1,m) {
int u,v;
cin >> u >> v;
add_edge(u,v);
cout << ans << endl;
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |