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>
#pragma GCC optimize("O3")
#pragma GCC target("avx2")
#define ll long long
#define pii pair<ll,ll>
#define pll pair<ll,ll>
#define plx pair<ll,int>
#define f first
#define s second
#define pb push_back
#define all(x) x.begin(),x.end()
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vi>
using namespace std;
const int mxn=2e5+5;
set<int>g[mxn],gr[mxn];
ll sz[mxn],pr[mxn];
int get(int r){
return pr[r]==r?r:pr[r]=get(pr[r]);
}vector<pii>qr;ll ans=0;
void ins(int a,int b){
if(g[a].count(b)||get(a)==get(b))return;
ans+=sz[b];
g[a].insert(b);
g[get(a)].insert(b);
gr[b].insert(a);
if(g[b].count(a))qr.pb({a,b});
}
void uni(int a,int b){
a=get(a),b=get(b);
if(a==b)return;
if(sz[a]+gr[a].size()+g[a].size()<sz[b]+g[b].size()+gr[b].size())swap(a,b);
ans+=sz[a]*(int)gr[b].size()+sz[b]*(int)gr[a].size();
pr[b]=a;sz[a]+=sz[b];
for(auto it : gr[b]){
if(gr[a].count(it))ans-=sz[a];
}
for(auto it : gr[b]){
if(g[a].count(it))ins(it,a);
}
for(auto it : g[b]){
if(gr[a].count(it))ins(a,it);
}
for(auto it : gr[b])gr[a].insert(it);
for(auto it : g[b])g[a].insert(it);
}
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;cin>>n>>m;
for(int i=1;i<=n;i++)pr[i]=i,sz[i]=1,gr[i].insert(i);
for(int i=1;i<=m;i++){
int a,b;cin>>a>>b;ins(a,get(b));
while(!qr.empty())uni(qr.back().f,qr.back().s),qr.pop_back();
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... |