제출 #1158846

#제출 시각아이디문제언어결과실행 시간메모리
1158846ace5조이터에서 친구를 만드는건 재밌어 (JOI20_joitter2)C++20
0 / 100
0 ms400 KiB
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

vector<set<int>> ine; //vertices
vector<set<int>> oute; //components
vector<vector<int>> comp;
vector<int> mycomp;
ll ans = 0;

ll func(int v)
{
    ll k = ine[v].size();
    ll szc = comp[v].size();
    return k * szc + szc*(szc-1);

}

void mrg(int u,int v)
{
    ans -= func(u);
    ans -= func(v);
    if(ine[u].size()+oute[u].size()+comp[u].size() > ine[v].size()+oute[v].size()+comp[v].size())
        swap(u,v);
    vector<pair<int,int>> nu;
    for(auto c:ine[u])
    {
        if(mycomp[c] != v)
        {
            if(oute[v].find(mycomp[c]) != oute[v].end())
            {
                nu.push_back({v,mycomp[c]});
            }
            ine[v].insert(c);
            oute[mycomp[c]].erase(u);
            oute[mycomp[c]].insert(v);
        }
    }
    for(auto c:oute[u])
    {
        if(c != v)
        {
            oute[v].insert(c);
            if(oute[c].find(u) != oute[c].end())
            {
                nu.push_back({v,c});
            }
        }
    }
    oute[v].erase(u);
    for(auto c:comp[u])
    {
        ine[v].erase(c);
        comp[v].push_back(c);
        mycomp[c] = v;
    }
    ine[u].clear();
    oute[u].clear();
    comp[u].clear();
    ans += func(v);
    for(auto [x,y]:nu)
    {
        x = mycomp[x];
        y = mycomp[y];
        if(x != y)
            mrg(x,y);
    }
    return ;
}


int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n,m;
    cin >> n >> m;
    ine.resize(n);
    oute.resize(n);
    comp.resize(n);
    mycomp.resize(n);
    for(int j = 0;j < n;++j)
    {
        mycomp[j] = j;
        comp[j].push_back(j);
    }
    for(int j = 0;j < m;++j)
    {
        int u,v;
        cin >> u >> v;
        int u2 = u-1;
        u--;
        v--;
        u = mycomp[u];
        v = mycomp[v];
        if(u == v)
        {
            cout << ans << "\n";
            continue;
        }
        ans -= func(v);
        ine[v].insert(u2);
        oute[u].insert(v);
        ans += func(v);
        if(oute[v].find(u) != oute[v].end())
        {
            mrg(u,v);
        }
        cout << ans << "\n";
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...