#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+12;
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<< L[v].size()<<' '<<L[u].size()<<'\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);
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';
Union(Q.back().fi,Q.back().se);
Q.pop_back();
}
cout << res<<'\n';
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// freopen("1017G.inp","r",stdin);
// freopen("1017G.out","w",stdout);
int t=1;//cin >> t;
while (t--) {
sol();
}
}
/*
4 3
1 2
2 3
3 2
*/
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
43600 KB |
Output is correct |
2 |
Correct |
7 ms |
43600 KB |
Output is correct |
3 |
Incorrect |
7 ms |
43680 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
43600 KB |
Output is correct |
2 |
Correct |
7 ms |
43600 KB |
Output is correct |
3 |
Incorrect |
7 ms |
43680 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
43600 KB |
Output is correct |
2 |
Correct |
7 ms |
43600 KB |
Output is correct |
3 |
Incorrect |
7 ms |
43680 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |