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>
#define ll long long
#define sz(x) (signed)x.size()
#define pb push_back
#define ff first
#define ss second
#define endl '\n'
#define For(i,l,r) for(int i=l;i<=r;i++)
#define ForD(i,l,r) for(int i=r;i>=l;i--)
#define F "CHOLHH"
#define fio freopen(F".inp","r",stdin);freopen(F".out","w",stdout);
using namespace std;
#ifdef NCGM
#include<C:/NCGM/headers/debug.h>
#else
#define debug(...) "mmb"
#endif
const int N=1e5+3;
int n,m,f[N],f1[N],mmb[N];
ll ans=0;
map<int,int> mp[N],mp1[N];
vector<int> ahu;
int find_set(int u) {
return (f[u]<0?u:f[u]=find_set(f[u]));
}
int find_set1(int u) {
return (f1[u]<0?u:f1[u]=find_set(f1[u]));
}
void unite(int u,int v) {
int a=find_set(u),b=find_set(v);
if (a==b) return;
ans-=1LL*f[a]*(f[a]+1);
ans+=1LL*f[a]*mmb[a];
ans-=1LL*f[b]*(f[b]+1);
ans+=1LL*f[b]*mmb[b];
int a1=find_set1(u),b1=find_set1(v);
if (sz(mp[a])<sz(mp[b])) swap(a,b);
if (sz(mp1[a1])<sz(mp1[b1])) swap(a1,b1);
ahu.clear();
for(auto el: mp[b]) ahu.pb(el.ff);
for(auto el: mp1[b1]) {
int tmp=mp[el.ff][b1];
mp[el.ff][a1]=mp[el.ff][b1];
mp[el.ff].erase(mp[el.ff].find(b1));
}
for(auto el: ahu) {
mp1[el][a]=mp1[el][b];
mp1[el].erase(mp1[el].find(b));
}
for(auto el: mp[b]) {
mp[a][el.ff]+=el.ss;
mmb[a]+=el.ss;
}
mp[b].clear();
for(auto el: mp1[b1]) mp1[a1][el.ff]+=el.ss;
mp1[b1].clear();
if (mp1[a1].find(a1)!=mp1[a1].end()) mp1[a1].erase(mp1[a1].find(a1));
if (mp1[a1].find(b1)!=mp1[a1].end()) mp1[a1].erase(mp1[a1].find(b1));
if (mp[a].find(b)!=mp[a].end()) {
mmb[a]-=mp[a][b];
mp[a].erase(mp[a].find(b));
}
if (mp[a].find(a)!=mp[a].end()) {
mmb[a]-=mp[a][a];
mp[a].erase(mp[a].find(a));
}
f[a]+=f[b];
f[b]=a;
ans+=1LL*f[a]*(f[a]+1);
ans-=1LL*f[a]*mmb[a];
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
For(i,1,n) f[i]=f1[i]=-1;
For(i,1,m) {
int u,v;
cin >> u >> v;
if (find_set(u)==find_set(v) || mp[find_set(v)].count(find_set1(u))) {
cout << ans << endl;
continue;
}
mmb[find_set(v)]++;
ans-=f[find_set(v)];
mp[find_set(v)][find_set1(u)]++;
mp1[find_set1(u)][find_set(v)]++;
if (mp[find_set(u)].count(find_set1(v))) unite(u,v);
cout << ans << endl;
}
return 0;
}
Compilation message (stderr)
joitter2.cpp: In function 'void unite(int, int)':
joitter2.cpp:46:13: warning: unused variable 'tmp' [-Wunused-variable]
46 | int tmp=mp[el.ff][b1];
| ^~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |