Find the beginning of a number x can be accessed (based unordered_map of disjoint-set)

Title:
given n, q, (1 <= n <= 10 ^ 9, 1 <= q <= 10 ^ 6), n represents the number 1 ~ n are arranged in a row, then the q-th interrogation, interrogation 1 Action: set x inaccessible. 2 query operation: start of the first number of outputs can be accessed from x (including x)

Sample input
. 5. 3
. 1 2
2 2
2. 1
sample output
. 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;
} 

Resolve

By disjoint-set, when an operation is set to the current x root root x + 1, so that in operation 2, the number of x by finding the roots can be accurately x onward can be accessed first, if is to themselves, if it is behind a number of other, also found a number of their own roots, which represents it must be accessible, not 1 is set in operation, you can quickly. N can be a great find because, not so much open space, so use the map to keep the number, instead of the adjacent type of presence, and to find more efficient unordered_map speed, so use unordered_map.

Published 52 original articles · won praise 2 · Views 888

Guess you like

Origin blog.csdn.net/qq_44714572/article/details/100607400