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>
using namespace std;
#define all(fl) fl.begin(),fl.end()
#define pb push_back
#define fi first
#define se second
#define for1(i,j,k) for(int i=j;i<=k;i++)
#define for2(i,j,k) for(int i=j;i>=k;i--)
#define for3(i,j,k,l) for(int i=j;i<=k;i+=l)
#define lb lower_bound
#define ub upper_bound
#define sz(a) (int)a.size()
#define pii pair<int,int>
#define pli pair<long long,int>
#define gcd __gcd
#define lcm(x,y) x*y/__gcd(x,y)
#define pil pair<int,long long>
#define pll pair<long long,long long>
#define eb emplace_back
const int maxn=1e5+9;
set<pii>a[maxn];
//x->u
set<int>b[maxn];
//u->x
int f[maxn];
int findset(int u){
if (f[u]<0)return u;
return f[u]=findset(f[u]);
}
long long ans=0;
void add(int u,int v){
int x=findset(u),y=findset(v);
if (x==y)return;
auto it=a[y].lower_bound({x,-1});
if (it!=a[y].end()&&(*it).fi==x){
if (sz(a[x])+sz(b[x])<sz(a[y])+sz(b[y])){
swap(x,y);
swap(u,v);
}
vector<pii>ad;
for (auto p:a[y]){
//p.fi clique p.se thuoc y
b[p.fi].erase(p.se);
ans-=abs(f[p.fi]);
if (p.fi!=x)ad.pb({p.se,p.fi});
}
ans+=abs(f[y])*(2*(abs(f[x]))+sz(b[x])-sz(b[y]));
for (auto p:b[y]){
int pr=findset(p);
a[pr].erase({y,p});
if (pr!=x)ad.pb({pr,x});
}
f[x]+=f[y];
f[y]=x;
for (auto p:ad)add(p.fi,p.se);
}
else if (b[y].find(u)==b[y].end()){
ans+=abs(f[y]);
b[y].insert(u);
a[x].insert({y,u});
}
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
//freopen("temp.INP","r",stdin);
//freopen("temp.OUT","w",stdout);
int n,m;
cin>>n>>m;
for1(i,1,n)f[i]=-1;
for1(i,1,m){
int u,v;
cin>>u>>v;
add(u,v);
cout<<ans<<'\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |