#include <bits/stdc++.h>
using namespace std;
vector<int> rep;
vector<set<int>> repgraph;
vector<set<int>> revgraph;
vector<long long> rsize;
vector<vector<int>> rin;
long long sol = 0;
int finde(int i)
{
if (i != rep[i]) rep[i] = finde(rep[i]);
return rep[i];
}
int main()
{
int n, m;
cin >> n >> m;
rep.resize(n);
repgraph.assign(n, set<int>());
revgraph.assign(n, set<int>());
rin.assign(n, vector<int>());
rsize.assign(n, 1);
iota(rep.begin(), rep.end(), 0);
for (int i = 0; i < n; i++)
{
rin[i].push_back(i);
}
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
a--; b--;
if (finde(a)==finde(b))
{
cout << sol << "\n";
continue;
}
if (repgraph[finde(b)].find(finde(a))==repgraph[finde(b)].end())
{
//a is not contained in graph from b;
//connect a to all nodes in b
sol -= rsize[finde(b)]*revgraph[finde(b)].size();
repgraph[finde(a)].insert(finde(b));
revgraph[finde(b)].insert(a);
sol += rsize[finde(b)]*revgraph[finde(b)].size();
cout << sol << "\n";
continue;
}
queue<int> q;
q.push(a);
while (q.size())
{
a = q.front();
q.pop();
if (finde(a)==finde(b)) continue;
repgraph[finde(b)].erase(finde(a));
if (repgraph[finde(a)].size()>repgraph[finde(b)].size())
{
swap(a, b);
}
sol -= revgraph[finde(a)].size()*rsize[finde(a)];
sol -= revgraph[finde(b)].size()*rsize[finde(b)];
for (int ele:repgraph[finde(a)])
{
if(finde(ele)==finde(b)) continue;
if (repgraph[finde(ele)].find(finde(b))!= repgraph[finde(ele)].end()) q.push(ele);
repgraph[finde(b)].insert(finde(ele));
}
if (rin[finde(a)].size() > rin[finde(b)].size())
{
repgraph[finde(a)].swap(repgraph[finde(b)]);
swap(a, b);
}
for (int ele:rin[finde(a)])
{
rin[finde(b)].push_back(ele);
revgraph[finde(b)].erase(ele);
}
if (revgraph[finde(a)].size()>revgraph[finde(b)].size())
{
rin[finde(a)].swap(rin[finde(b)]);
repgraph[finde(a)].swap(repgraph[finde(b)]);
swap(a, b);
}
for (int ele:revgraph[finde(a)])
{
repgraph[finde(ele)].erase(finde(a));
if (repgraph[finde(b)].find(finde(ele))!= repgraph[finde(b)].end()) q.push(ele);
else if (finde(ele) != finde(b) && finde(ele)!=finde(a))
{
repgraph[finde(ele)].insert(finde(b));
revgraph[finde(b)].insert(ele);
}
}
sol += rsize[finde(a)]*rsize[finde(b)]*2;
int sum = rsize[finde(a)]+rsize[finde(b)];
rsize[finde(a)] = sum;
rsize[finde(b)] = sum;
rep[finde(a)] = rep[finde(b)];
sol += revgraph[finde(b)].size()*rsize[finde(b)];
}
cout << sol << "\n";
}
return 0;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
0 ms |
344 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |