/*
IN THE NAME OF GOD
*/
#include <bits/stdc++.h>
// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef long double ld;
#define F first
#define S second
#define Mp make_pair
#define pb push_back
#define pf push_front
#define size(x) ((ll)x.size())
#define all(x) (x).begin(),(x).end()
#define kill(x) cout << x << '\n', exit(0);
#define fuck(x) cout << "(" << #x << " , " << x << ")" << endl
#define endl '\n'
const int N = 3e5+23, lg = 18;
ll Mod = 1e9+7; //998244353;
inline ll MOD(ll a, ll mod=Mod) {a%=mod; (a<0)&&(a+=mod); return a;}
inline ll poww(ll a, ll b, ll mod=Mod) {
ll ans = 1;
a=MOD(a, mod);
while (b) {
if (b & 1) ans = MOD(ans*a, mod);
b >>= 1;
a = MOD(a*a, mod);
}
return ans;
}
ll n, m, ans, sz[N], par[N];
set<pii> st[N], str[N];
set<int> eout[N], ein[N];
int getPar(int v) {return (par[v]==0 ? v : par[v]=getPar(par[v]));}
void merge(int v, int u) {
if(sz[v] < sz[u]) swap(v,u);
ans += (2ll*sz[v]*sz[u]);
par[u] = v;
for(auto it : st[u]) st[v].insert(it);
for(auto it : str[u]) str[v].insert(it);
ll tmp = 0, tmp2 = size(ein[v]);
for(auto it : ein[u]) {
int tt = getPar(it);
st[tt].erase({it, u});
str[tt].erase({u, it});
st[tt].insert({it, v});
str[tt].insert({v, it});
eout[tt].erase(u);
eout[tt].insert(v);
if(ein[v].find(it) != ein[v].end()) tmp++;
else {
ein[v].insert(it);
ans += sz[v];
}
}
//fuck(ans);
ans += ((tmp2 - tmp) * sz[u]);
sz[v] += sz[u];
}
int main () {
ios_base::sync_with_stdio(false), cin.tie(0);
cin>>n>>m;
fill(sz+1, sz+n+1, 1);
for(int v,u,i=1; i<=m; i++) {
cin>>v>>u;
if(getPar(v)!=getPar(u)) {
int pv=getPar(v), pu=getPar(u);
if(eout[pu].find(pv) != eout[pu].end()) {
while(true) {
auto it = str[pu].lower_bound({pv, 0});
if(it==str[pu].end()||(*it).F!=pv) break;
ein[pv].erase((*it).S);
ans -= sz[pv];
st[pu].erase({(*it).S, (*it).F});
str[pu].erase((*it));
}
eout[pu].erase(pv);
merge(pu, pv);
} else {
eout[pv].insert(pu);
if(st[pv].find({v, pu}) == st[pv].end()) {
ein[pu].insert(v);
st[pv].insert({v, pu});
str[pv].insert({pu, v});
ans += sz[pu];
}
}
}
cout<<ans<<endl;
// if(i == 8) {
// for(int j=1; j<=n; j++) fuck(getPar(j));
// }
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
18 ms |
57944 KB |
Output is correct |
2 |
Correct |
17 ms |
57948 KB |
Output is correct |
3 |
Incorrect |
17 ms |
57948 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
18 ms |
57944 KB |
Output is correct |
2 |
Correct |
17 ms |
57948 KB |
Output is correct |
3 |
Incorrect |
17 ms |
57948 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
18 ms |
57944 KB |
Output is correct |
2 |
Correct |
17 ms |
57948 KB |
Output is correct |
3 |
Incorrect |
17 ms |
57948 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |