#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n, m; cin>>n>>m;
vector<int> p(n + 1), sz(n + 1);
for (int i = 1; i <= n; i++){
p[i] = i;
sz[i] = 1;
}
function<int(int)> get = [&](int v){
if (p[v] != v){
p[v] = get(p[v]);
}
return p[v];
};
set<int> a[n + 1], b[n + 1], c[n + 1];
ll out = 0;
// b is outgoing
// c is ingoing
function<void(int, int)> merge = [&](int x, int y){
if (p[x] != x || p[y] != y) return;
out -= 1LL * sz[x] * (sz[x] + a[x].size() - 1);
out -= 1LL * sz[y] * (sz[y] + a[y].size() - 1);
if (sz[x] < sz[y]) swap(x, y);
p[y] = x;
sz[x] += sz[y];
for (int i: a[y]) a[x].insert(i);
vector<int> all;
for (int i: b[y]){
if (b[i].find(x) != b[i].end()){
all.pb(i);
}
b[x].insert(i);
}
for (int i: c[y]){
if (c[i].find(x) != c[i].end()){
all.pb(i);
}
c[x].insert(i);
}
a[x].erase(x); a[x].erase(y);
b[x].erase(x); b[x].erase(y);
c[x].erase(x); c[x].erase(y);
out += 1LL * sz[x] * (sz[x] + a[x].size() - 1);
for (int i: all) merge(x, i);
};
while (m--){
int x, y; cin>>x>>y;
int x1 = get(x), y1 = get(y);
if (a[y1].find(x) == a[y1].end()){
out += sz[y1];
a[y1].insert(x);
}
if (b[y1].find(x1) != b[y1].end()){
merge(x1, y1);
}
else {
b[x1].insert(y1);
c[y1].insert(x1);
}
cout<<out<<"\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... |