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;
typedef long long ll;
typedef pair<int, int> pii;
const int MAXN = 1e5;
const int MAXM = 3e5;
vector<int> contained[MAXN];
vector<int> out_edges[MAXN];
vector<int> in_edges[MAXN];
int uf[MAXN];
set<int> inc[MAXN]; // specific nodes
set<int> out[MAXN]; // this is just general ccs
ll ans = 0;
int n, m;
void undo(int i) {
ans -= (ll)contained[i].size()*inc[i].size();
ans -= (ll)contained[i].size()*((int)contained[i].size()-1);
}
void make(int i) {
ans += (ll)contained[i].size()*inc[i].size();
ans += (ll)contained[i].size()*((int)contained[i].size()-1);
}
void merge(int a, int b) {
a = uf[a];
b = uf[b];
if (a == b) return;
if (contained[a].size() < contained[b].size()) swap(a, b);
undo(a);
undo(b);
out[a].erase(b);
out[b].erase(a);
for (int v: contained[b]) {
inc[a].erase(v);
uf[v] = a;
contained[a].push_back(v);
}
for (int w: inc[b]) {
if (uf[w] != a) {
inc[a].insert(w);
out[uf[w]].insert(a);
out[uf[w]].erase(b);
}
}
for (int w: out[b]) {
out[a].insert(w);
}
make(a);
vector<int> ex;
for (int v: inc[b]) {
if (out[a].find(uf[v]) != out[a].end()) ex.push_back(v);
}
for (int v: out[b]) {
if (out[v].find(a) != out[v].end()) ex.push_back(v);
}
out[b].clear();
inc[b].clear();
contained[b].clear();
for (int v: ex) merge(v, a);
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
cin >> n >> m;
iota(uf, uf+n, 0);
for (int i = 0; i < n; i++) contained[i].push_back(i);
for (int i = 0; i < m; i++) {
int x, y; cin >> x >> y;
x--; y--;
if (uf[x] != uf[y]) {
if (out[uf[y]].find(uf[x]) != out[uf[y]].end()) {
merge(x, y);
}
else {
undo(uf[y]);
inc[uf[y]].insert(x);
make(uf[y]);
out[uf[x]].insert(uf[y]);
}
}
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... |