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 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 int long long
typedef long long ll;
typedef pair<int,int> pii;
const ll maxn=3e5+10;
const ll offset=2e5;
const ll inf=1e18;
const int base=350;
const ll mod=998244353;
int n,m;
int par[maxn];
set<int> adj[maxn],adj_r[maxn],L[maxn];
int res;
vector<pii> Q;
int Find(int u)
{
return par[u]<0?u:par[u]=Find(par[u]);
}
void Union(int u,int v)
{
if ((u=Find(u))==(v=Find(v))) return;
if (L[u].size() + adj[u].size() + adj_r[u].size() < L[v].size()+adj[v].size()+adj_r[v].size()) swap(u,v);
res+=-par[u]*L[v].size() - par[v]*L[u].size();
// cerr<<u<<' '<<v<<' '<< res<<'\n';
par[u]+=par[v];
par[v]=u;
for(int x: L[v])
{
if (L[u].find(x)!=L[u].end())
{
res+=par[u];
continue;
}
L[u].insert(x);
}
L[v].clear();
adj[u].erase(v);adj_r[u].erase(v);adj[v].erase(u);adj_r[v].erase(u);
for(int x:adj[v])
{
// x=Find(x);
adj[u].insert(x);
adj_r[x].insert(u);
if (adj_r[u].find(x)!=adj_r[u].end()) Q.pb({u,x});
}
// adj[v].clear();
for(int x:adj_r[v])
{
// x=Find(x);
adj_r[u].insert(x);
adj[x].insert(u);
// cerr<< adj[u].count(x)<<'\n';
if (adj[u].find(x)!=adj[u].end()) Q.pb({u,x});
}
// adj_r[v].clear();
}
void sol()
{
cin >>n>>m;
for1(i,1,n)
{
par[i]=-1;
L[i].insert(i);
}
for1(i,1,m)
{
int u,v;cin >> u>> v;
v=Find(v);
if (u==v || L[v].find(u)!=L[v].end()) cout << res<<'\n';
else
{
L[v].insert(u);
u=Find(u);
adj[u].insert(v);
adj_r[v].insert(u);
res-=par[v];
// cerr<< res<<" ashiba\n";
if (adj_r[u].find(v)!=adj_r[u].end()) Q.pb({u,v});
while (!Q.empty())
{
// cerr<<" ulion "<<Q.back().fi<<' '<<Q.back().se<<'\n';
pii x=Q.back();
Q.pop_back();
Union(x.fi,x.se);
}
cout << res<<'\n';
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// freopen("adfaf.inp","r",stdin);
// freopen("adfaf.out","w",stdout);
int t=1;//cin >> t;
while (t--) {
sol();
}
}
/*
4 3
1 2
2 3
3 2
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |