F. Asya And Kittens(思维+树形构造+启发式合并)

https://codeforces.com/problemset/problem/1131/F


思路:

对于每一个编号,我们将其连边都看作他的儿子,然后将儿子的状态最后都更新到他本身。

看成他的儿子就变成了树形结构。这里借用大佬的图

对于 1 3 1 2 4 5 4 6 1 4
G[1] = {3,2,4},每个子树都保证顺序可行,那么合并起来的顺序也是可行的。

在这里插入图片描述

可以看到,这样子构造一定是合法的。问题就变成了如何将每个点不是n^2更新。启发式合并,大儿子不删,将小儿子的集合状态都累加到大儿子集合离去,然后删掉小儿子。O(nlogn)

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+100;
typedef int LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL fa[maxn];
vector<LL>g[maxn];
LL find(LL x){
    if(x!=fa[x]) return fa[x]=find(fa[x]);
    return fa[x];
}
LL dsu(LL x,LL y){
    LL px=find(x);LL py=find(y);///找到根节点
    if(g[px].size()>g[py].size()){
        swap(px,py);///令包含元素少的为x节点
    }
    fa[px]=py;
    g[py].insert(g[py].end(),g[px].begin(),g[px].end());///插入大元素的儿子集合的右边
    g[px].clear();
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n;cin>>n;
  for(LL i=1;i<=n;i++) fa[i]=i,g[i].push_back(i);
  for(LL i=1;i<n;i++){
    LL u,v;cin>>u>>v;
    dsu(u,v);
  }
  LL id=find(1);
  for(auto i:g[id]){
     cout<<i<<" ";
  }
  cout<<"\n";
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/115023699