[CF1131F] Asya And Kittens

Description:

给定n个点的序列,一开始有n个块,每次将两个块合并,并告诉你这两个块中的一对元素,求一种可能的原序列

Hint:

\(n \le 1.5*10^5\)

Solution:

实在是SB题
考虑把每对点的祖先连上一个虚点,用并查集维护,最后dfs所得的树就行
为什么是对的,因为这棵树会按时间顺序由下往上合并节点
好像还有一种做法,对每个块的祖先维护一个vector表示顺序,合并时启发式合并,复杂度\(O(nlogn)\)


#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define ls p<<1 
#define rs p<<1|1
using namespace std;
typedef long long ll;
const int mxn=1e6+5; //空间开大点
int n,hd[mxn],f[mxn],p,cnt;
inline int read() {
    char c=getchar(); int x=0,f=1;
    while(c>'9'||c<'0') {if(c=='-') f=-1;c=getchar();}
    while(c<='9'&&c>='0') {x=(x<<3)+(x<<1)+(c&15);c=getchar();}
    return x*f;
}
inline int chkmax(int &x,int y) {if(x<y) x=y;}
inline int chkmin(int &x,int y) {if(x>y) x=y;}

struct ed {
    int to,nxt;
}t[mxn<<1];

inline void add(int u,int v) {
    t[++cnt]=(ed) {v,hd[u]}; hd[u]=cnt;
}

inline int find(int x) 
{
    return f[x]==x?x:f[x]=find(f[x]);
}

void dfs(int u)
{
    if(u<=n) printf("%d ",u); 
    for(int i=hd[u];i;i=t[i].nxt) {
        int v=t[i].to;
        dfs(v);
    }
}

int main()
{
    n=read(); p=n; int u,v,x,y;
    for(int i=1;i<=mxn-2;++i) f[i]=i;
    for(int i=1;i<n;++i) {
        u=read(); v=read();
        x=find(u),y=find(v);
        f[x]=f[y]=++p;
        add(p,x); add(p,y);
    }
    dfs(p);
    return 0;
}

转载于:https://www.cnblogs.com/list1/p/10509912.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值