Submission #1312039

#TimeUsernameProblemLanguageResultExecution timeMemory
1312039vladiliusMaking Friends on Joitter is Fun (JOI20_joitter2)C++20
0 / 100
1 ms332 KiB
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define pb push_back
#define ff first
#define ss second

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    
    int n, m; cin>>n>>m;
    
    vector<int> p(n + 1), sz(n + 1);
    for (int i = 1; i <= n; i++){
        p[i] = i;
        sz[i] = 1;
    }
    
    function<int(int)> get = [&](int v){
        if (p[v] != v){
            p[v] = get(p[v]);
        }
        return p[v];
    };
    
    set<int> a[n + 1], b[n + 1], c[n + 1];
    
    // b is outgoing
    // c is ingoing
    
    function<void(int, int)> merge = [&](int x, int y){
        x = get(x); y = get(y);
        if (x == y) return;
        // out -= 1LL * sz[x] * (sz[x] + a[x].size() - 1);
        // out -= 1LL * sz[y] * (sz[y] + a[y].size() - 1);
        
        if (sz[x] < sz[y]) swap(x, y);
        
        p[y] = x;
        sz[x] += sz[y];

        for (int i: a[y]) a[x].insert(i);
        
        vector<int> all;
        for (int i: b[y]){
            if (b[i].find(x) != b[i].end()){
                all.pb(i);
            }
            b[x].insert(i);
        }
        
        for (int i: c[y]){
            if (c[i].find(x) != c[i].end()){
                all.pb(i);
            }
            c[x].insert(i);
        }

        a[x].erase(a[x].find(x)); a[x].erase(a[x].find(y));
        b[x].erase(b[x].find(x)); b[x].erase(b[x].find(y));
        c[x].erase(c[x].find(x)); c[x].erase(c[x].find(y));
        
        for (int i: b[x]){
            assert(i == get(i));
        }


        // out += 1LL * sz[x] * (sz[x] + a[x].size() - 1);
        
        for (int i: all) merge(x, i);
    };
    
    while (m--){
        int x, y; cin>>x>>y;
        
        int x1 = get(x), y1 = get(y);
        
        if (x1 != y1){
            a[y1].insert(x);
            b[x1].insert(y1);
            c[y1].insert(x1);
            
            if (b[y1].find(x1) != b[y1].end()){
                merge(x1, y1);
            }
        }
        
        ll out = 0;
        for (int i = 1; i <= n; i++){
            if (i == get(i)){
                out += 1LL * sz[i] * (sz[i] + a[i].size() - 1);
            }
        }
        
        cout<<out<<"\n";
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...