Submission #1161084

#TimeUsernameProblemLanguageResultExecution timeMemory
1161084HanksburgerMaking Friends on Joitter is Fun (JOI20_joitter2)C++20
100 / 100
535 ms68456 KiB
#include <bits/stdc++.h>
#define int long long
using namespace std;
set<int> child[100005], s[100005], t[100005];
int par[100005], sz[100005];
queue<pair<int, int> > q;
int findPar(int u)
{
    return par[u]==u?u:par[u]=findPar(par[u]);
}
void add(int x, int y)
{
    s[x].insert(y);
    t[y].insert(x);
    if (s[y].find(x)!=s[y].end())
        q.push({x, y});
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n, m, ans=0;
    cin >> n >> m;
    for (int i=1; i<=n; i++)
    {
        child[i].insert(i);
        par[i]=i;
        sz[i]=1;
    }
    for (int i=0; i<m; i++)
    {
        int u, v;
        cin >> u >> v;
        int x=findPar(u), y=findPar(v);
        if (x!=y)
        {
            if (child[y].find(u)==child[y].end())
            {
                child[y].insert(u);
                ans+=sz[y];
            }
            add(x, y);
            while (!q.empty())
            {
                x=findPar(q.front().first), y=findPar(q.front().second);
                q.pop();
                if (x==y)
                    continue;
                if (sz[x]>sz[y])
                    swap(x, y);
                ans+=child[x].size()*sz[y]+child[y].size()*sz[x];
                for (int w:child[x])
                {
                    if (child[y].find(w)==child[y].end())
                        child[y].insert(w);
                    else
                        ans-=sz[x]+sz[y];
                }
                s[x].erase(y);
                s[y].erase(x);
                t[x].erase(y);
                t[y].erase(x);
                for (int w:s[x])
                {
                    t[w].erase(x);
                    add(y, w);
                }
                for (int w:t[x])
                {
                    s[w].erase(x);
                    add(w, y);
                }
                par[x]=y;
                sz[y]+=sz[x];
            }
        }
        cout << ans << '\n';
    }
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...