#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll ans;
int n, m, u, v, sz[100001], par[100001];
set<int> followers[100001];
int find(int x) { return x == par[x] ? x : par[x] = find(par[x]); }
void unite(int x, int y) {
if ((x = find(x)) == (y = find(y))) return;
if (sz[x] > sz[y]) swap(x, y);
ans += (ll)(sz[x]+sz[y])*(sz[x]+sz[y]-1) - (ll)sz[y]*(sz[y]-1) - (ll)sz[x]*(sz[x]-1);
ans -= (ll)followers[x].size()*sz[x] + (ll)followers[y].size()*sz[y];
par[x] = y;
sz[y] += sz[x];
if (followers[x].size() > followers[y].size()) followers[x].swap(followers[y]);
followers[y].insert(followers[x].begin(), followers[x].end());
vector<int> rm;
for (auto e: followers[y]) if (find(e) == y) rm.push_back(e);
for (auto e: rm) followers[y].erase(e);
ans += (ll)followers[y].size()*sz[y];
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
for (int i = 1; i < 100001; i++) par[i] = i, sz[i] = 1;
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> u >> v;
if (find(u) != find(v) && !followers[find(v)].count(u)) {
followers[find(v)].insert(u);
ans += sz[find(v)];
if (followers[find(u)].count(v)) unite(u, v);
}
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... |