查找x开始的一个可以访问的数(基于unordered_map的并查集)

题目:
给出n,q,(1<= n <= 10^9, 1 <= q <= 10 ^6), n代表1~n的数排成一排,然后进行q次询问,询问1操作:将x设为不可访问。询问操作2:输出从x开始第一个可以访问的数(包括x)

样例输入
5 3
1 2
2 2
2 1
样例输出
3
1

#include <cstdio>
#include <unordered_map>
using namespace std;
unordered_map<int , int> pre;
int find(int x){
	if(!pre.count(x)) return x;
	return pre[x] = find(pre[x]);
}
int main(){
	int n, q;
	int op, x, ans;
	scanf("%d %d", &n, &q);
	while(q--){
		scanf("%d %d", &op, &x);
		if(op == 1){
			pre[x] = find(x+1);
		}
		else{
			ans = find(x);
			if(x > n)
				printf("-1\n");
			else
				printf("%d\n", ans); 
		}
	}
	return 0;
} 

解析

通过并查集, 当进行操作1时将当前x的根设为x+1的根,这样在操作2,通过查找x的根就可以确地x开始往后第一个可以访问的数,如果是自己就是自己,如果是其它后面的数,找到的也是一个数是自己的根, 这代表它必然可以访问,没有在操作1里被设置,就可以快速。找到因为n可以很大,开不了这么大空间, 所以要用map来存数,代替相邻式的存在,而unordered_map查找效率速度更高,所以使用unordered_map。

发布了52 篇原创文章 · 获赞 2 · 访问量 888

猜你喜欢

转载自blog.csdn.net/qq_44714572/article/details/100607400