UNICORN Programming Contest 2021(AtCoder Beginner Contest 225) D - Play Train

本文介绍了一种数据结构的实现,即并查集与前驱链表的结合,用于处理合并与查找操作。在给定的C++代码中,通过find_ne()和find_pre()函数实现了查找最近合并点和前驱节点的功能。在主函数中,针对不同的查询类型(合并、解除合并、查找路径)进行处理,并输出路径长度及节点顺序。该数据结构在图论和树形结构操作中有广泛应用。
摘要由CSDN通过智能技术生成

类似于并查集一个ne数组一个pre数组,不能按秩合并或者路径压缩

#include<unordered_set>
#include<unordered_map>
#include<functional>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<iterator>
#include<cstring>
#include<numeric> 
#include<cstdio>
#include<vector>
#include<bitset>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
#include<deque>

using namespace std;
//================================
#define debug(a) cout << #a": " << a << endl;
#define rep(i, ll,rr) for(int i = ll; i <= rr; ++i)
#define N 100010
//================================
typedef pair<int,int> pii;
#define x first
#define y second
typedef long long LL; typedef unsigned long long ULL; typedef long double LD;
inline LL read() { LL s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar())    s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
inline void print(LL x, int op = 10) { if (!x) { putchar('0'); if (op)  putchar(op); return; }  char F[40]; LL tmp = x > 0 ? x : -x; if (x < 0)putchar('-');  int cnt = 0;    while (tmp > 0) { F[cnt++] = tmp % 10 + '0';     tmp /= 10; }    while (cnt > 0)putchar(F[--cnt]);    if (op) putchar(op); }
LL fpower(LL a,LL b,LL mod) {LL ans = 1; while(b){ if(b & 1) ans = ans * (a % mod) % mod; a = a % mod * (a % mod) % mod; b >>= 1;} return ans; } LL Mod(LL a,LL mod){return (a%mod+mod)%mod;}
//================================= 
int n,q,ne[N],pre[N],id,x,y;

int find_ne(int x){
	return ne[x]==x?ne[x]:find_ne(ne[x]);
}

int find_pre(int x){
	return pre[x] == x?pre[x]:find_pre(pre[x]);
}
//=================================
int main(){
	n = read(), q = read();
    rep(i,1,n) ne[i] = i,pre[i] = i;
    rep(i,1,q){
    	id = read();
    	if(id==1){
    		x = read(),y = read();
    		ne[y]=x;
    		pre[x]=y;
    	}
    	else if(id==2){
    		x = read(),y = read();
    		ne[y] = y;
    		pre[x]=x;
    	}
    	else{
    		x = read();
    		x = find_ne(x);
    		
    		queue<int> Q;
    		while(Q.size()) Q.pop();
    		
    		int p = x;
    		while(p!=pre[p]){
    			Q.push(p);
    			p = pre[p];
    		}
    		Q.push(p);
    		printf("%d ",Q.size());
    		while(Q.size()){
    			printf("%d ",Q.front());
    			Q.pop();
    		}
    		puts("");
    	}
    }
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值