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;
using ll = long long;
using ld = long double;
using str = string;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<ld, ld>;
#define mp make_pair
#define ff first
#define ss second
template<class T> using V = vector<T>;
#define arr array
using vi = V<int>;
using vb = V<bool>;
using vl = V<ll>;
using vd = V<ld>;
using vs = V<str>;
using vpi = V<pi>;
using vpl = V<pl>;
using vpd = V<pd>;
#define sz(x) (int)((x).size())
#define bg(x) begin(x)
#define all(x) bg(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define sor(x) sort(all(x))
#define rsz resize
#define ins insert
#define pb push_back
#define eb emplace_back
#define ft front()
#define bk back()
#define lb lower_bound
#define ub upper_bound
#define FOR(i, a, b) for(int i = (a); i < (b); ++i)
#define F0R(i, a) FOR(i, 0, a)
#define ROF(i, a, b) for(int i = (b) - 1; i >= (a); --i)
#define R0F(i, a) ROF(i, 0, a)
#define rep(a) F0R(_, a)
#define trav(a, x) for(auto& a : x)
template<class T> bool ckmin(T& a, const T& b) { return (b < a ? a = b, 1 : 0); }
template<class T> bool ckmax(T& a, const T& b) { return (b > a ? a = b, 1 : 0); }
#define int long long
const int maxn = 1e5;
int N, M, ans;
queue<pi> q;
int bulgem[maxn], ataman[maxn];
set<int> radj[maxn], adj[maxn], K[maxn];
int parent(int A) {
return (A == ataman[A] ? A : ataman[A] = parent(ataman[A]));
}
void merge_comp(int A, int B) {
A = parent(A); B = parent(B);
if(A == B) return;
ans += 1LL * bulgem[A] * sz(K[B]) + 1LL * bulgem[B] * sz(K[A]);
if(sz(K[A]) < sz(K[B])) swap(A, B);
trav(u, K[B]) {
if(K[A].find(u) != end(K[A])) ans -= 1LL * (bulgem[A] + bulgem[B]);
else K[A].ins(u);
}
adj[A].erase(B);
adj[B].erase(A);
radj[A].erase(B);
radj[B].erase(A);
trav(u, adj[B]) {
radj[u].erase(B);
adj[A].ins(u);
radj[u].ins(A);
if(adj[u].find(A) != end(adj[u])) q.push({u, A});
}
trav(u, radj[B]) {
adj[u].erase(B);
radj[A].ins(u);
adj[u].ins(A);
if(adj[A].find(u) != end(adj[A])) q.push({u, A});
}
bulgem[A] += bulgem[B];
ataman[B] = A;
}
void add_edge(int A, int B) {
B = parent(B);
if(K[B].find(A) != end(K[B])) return;
ans += bulgem[B];
K[B].ins(A);
A = parent(A);
adj[A].ins(B);
radj[B].ins(A);
if(adj[B].count(A)) merge_comp(A, B);
}
int32_t main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M; cin >> N >> M;
F0R(i, N) {
ataman[i] = i;
bulgem[i] = 1;
K[i].ins(i);
}
F0R(i, M) {
int u, v; cin >> u >> v;
--u; --v;
add_edge(u, v);
while(!q.empty()) {
tie(u, v) = q.ft;
q.pop();
merge_comp(u, v);
}
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... |