This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/**
* author: NimaAryan
* created: 2024-08-15 13:30:23
**/
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "algo/debug.h"
#endif
using i64 = long long;
i64 ans = 0;
vector<set<int>> S;
vector<set<int>> T;
vector<set<int>> G;
vector<int> par;
queue<pair<int, int>> to_merge;
int find(int x) {
return par[x] == -1 ? x : par[x] = find(par[x]);
}
inline int size(int A) {
return S[A].size() + T[A].size() + G[A].size();
}
void unite(int A, int B) {
A = find(A), B = find(B);
if (A == B) {
return;
}
if (size(A) < size(B)) {
swap(A, B);
}
ans -= 1LL * S[A].size() * (S[A].size() - 1);
ans -= 1LL * S[A].size() * T[A].size();
ans -= 1LL * S[B].size() * (S[B].size() - 1);
ans -= 1LL * S[B].size() * T[B].size();
G[A].erase(B);
for (int X : G[B]) {
if (X == A) {
continue;
}
if (G[X].count(A)) {
to_merge.emplace(A, X);
}
G[A].insert(X);
}
for (int x : T[B]) {
int X = find(x);
if (X == A) {
continue;
}
T[A].insert(x);
if (G[A].count(X)) {
to_merge.emplace(A, X);
}
G[X].erase(B);
G[X].insert(A);
}
for (int b : S[B]) {
T[A].erase(b);
S[A].insert(b);
}
par[B] = A;
ans += 1LL * S[A].size() * (S[A].size() - 1);
ans += 1LL * S[A].size() * T[A].size();
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
S.resize(n);
for (int x = 0; x < n; ++x) {
S[x] = {x};
}
T.resize(n);
G.resize(n);
par.assign(n, -1);
while (m--) {
int a, b;
cin >> a >> b;
--a, --b;
int A = find(a), B = find(b);
if (A != B) {
if (G[B].count(A)) {
unite(A, B);
} else if (!T[B].count(a)) {
ans += S[B].size();
T[B].insert(a);
G[A].insert(B);
}
while (!to_merge.empty()) {
auto [X, Y] = to_merge.front();
to_merge.pop();
unite(X, Y);
}
}
cout << ans << "\n";
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |