Submission #1294770

#TimeUsernameProblemLanguageResultExecution timeMemory
1294770rcllMaking Friends on Joitter is Fun (JOI20_joitter2)C++20
100 / 100
516 ms65732 KiB
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

int cmp[100001];
ll sz[100001],ans=0;
set<int> child[100001],graph[100001],reverse_graph[100001];
queue<pair<int,int>> todo;

void connect(int a,int b) {
    graph[a].insert(b);
    reverse_graph[b].insert(a);
    if (graph[b].count(a)) {
        todo.push({a,b});
    }
}

int dsu_size(int a) {
    return child[a].size()+graph[a].size()+reverse_graph[a].size();
}

int find(int a) {
    return (a==cmp[a] ? a : cmp[a]=find(cmp[a]));
}

void merge(int a,int b) {
    if (a==b) {
        return;
    }
    if (dsu_size(a) < dsu_size(b)) {
        swap(a,b);
    }
    ans+=sz[b]*child[a].size()+sz[a]*child[b].size();
    cmp[b]=a;
    sz[a]+=sz[b];
    for (int i : child[b]) {
        if (child[a].count(i)) {
            ans-=sz[a];
        } else {
            child[a].insert(i);
        }
    }
    graph[a].erase(b);
    reverse_graph[a].erase(b);
    graph[b].erase(a);
    reverse_graph[b].erase(a);
    for (int i : graph[b]) {
        reverse_graph[i].erase(b);
        connect(a,i);
    }
    for (int i : reverse_graph[b]) {
        graph[i].erase(b);
        connect(i,a);
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n,m;
    cin >> n >> m;
    for (int i=1; i<=n; i++) {
        cmp[i]=i;
        sz[i]=1;
        child[i].insert(i);
    }
    while (m--) {
        int a,b;
        cin >> a >> b;
        b=find(b);
        if (find(a) != b && !child[b].count(a)) {
            child[b].insert(a);
            ans+=sz[b];
            a=find(a);
            connect(a,b);
            while (todo.size()) {
                tie(a,b)=todo.front();
                todo.pop();
                merge(find(a),find(b));
            }
        }
        cout << ans << '\n';
    }
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...