#include<bits/stdc++.h>
#define ld long double
#define pii pair<long long,int>
#define pll pair<ll,ll>
#define all(x) x.begin(),x.end()
#define pb push_back
#define f first
#define s second
#define vi vector<ll>
#define vvi vector<vi>
#define vpii vector<pii>
#define ll long long
#define siz(x) (ll)x.size()
using namespace std;
const int N=1e5+5;
ll pr[N],sz[N];
ll ans=0;
set<int>g[N],rg[N],ch[N];
int get(int r){
return pr[r]==r?r:pr[r]=get(pr[r]);
}vector<pii>mer;
void addedge(int a,int b){
g[a].insert(b);rg[b].insert(a);
if(g[b].count(a))mer.pb({a,b});
}
int gsz(int x){
return ch[x].size()+g[x].size()+rg[x].size();
}
void uni(int a,int b){
if(a==b)return;
if(gsz(a)<gsz(b))swap(a,b);
ans += siz(ch[a])*sz[b]+siz(ch[b])*sz[a];
pr[b]=a;sz[a]+=sz[b];
for(auto it : ch[b]){
if(ch[a].count(it))ans-=sz[a];
else ch[a].insert(it);
}g[b].erase(a);rg[b].erase(a);g[a].erase(b);rg[a].erase(b);
for(auto it : g[b]){
addedge(a,it);
}
for(auto it : rg[b]){
addedge(it,a);
}
}
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,ch[i].insert(i);
while(m--){
int a,b;cin>>a>>b;
b=get(b);
if(a==b||ch[b].count(a)){
cout<<ans<<'\n';
continue;
}ch[b].insert(a);
ans+=sz[b];a=get(a);
addedge(a,b);
while(!mer.empty()){
uni(get(mer.back().f),get(mer.back().s));mer.pop_back();
}cout<<ans<<'\n';
}
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
5 ms |
14940 KB |
Output is correct |
2 |
Correct |
5 ms |
15000 KB |
Output is correct |
3 |
Incorrect |
5 ms |
14940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
5 ms |
14940 KB |
Output is correct |
2 |
Correct |
5 ms |
15000 KB |
Output is correct |
3 |
Incorrect |
5 ms |
14940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
5 ms |
14940 KB |
Output is correct |
2 |
Correct |
5 ms |
15000 KB |
Output is correct |
3 |
Incorrect |
5 ms |
14940 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |