1459: [蓝桥杯2019初赛]修改数组

2019省赛A组第8题 修改数组

题目链接http://oj.ecustacm.cn/problem.php?id=1459

#include<iostream>
#define N 100010
using namespace std;
int a[N];
int b[N];
int find(int x) {
    
    //递归查找
	if (x != b[x]) {
    
    
		b[x] = find(b[x]);
	}
	return b[x];
}
int find_2(int x) {
    
    //非递归查找
	int t = x;
	while (t != b[t]) t = b[t];
	int i = x;
	while (i != t) {
    
    
		int j = b[i];
		b[i] = t;
		i = j;
	}
	return t;
}
void merge(int x,int y) {
    
    //合并,本题没有用到
	int xx = find(x);
	int yy = find(y);
	b[xx] = yy;
}
int main() {
    
    
	int n;
	for (int i = 1; i < N; i++) {
    
    
		b[i] = i;
	}
	cin >> n;
	for (int i = 1; i <= n; i++) {
    
    
		cin >> a[i];
	}
	for (int i = 1; i <= n; i++) {
    
    
		int t = find_2(a[i]);
		a[i] = t;
		b[t] = find_2(t + 1);//b[t]这个数已经被使用,所以要替换,寻找下一个
	}
	for (int i = 1; i <= n; i++) {
    
    
		cout << a[i] << " ";
	}


	return 0;
}

罗老师代码链接https://blog.csdn.net/weixin_43914593/article/details/112979670
并查集资料链接https://blog.csdn.net/weixin_43914593/article/details/104108049

猜你喜欢

转载自blog.csdn.net/weixin_46028214/article/details/113593016