蓝桥杯 修改数组 标签:并查集

80 阅读1分钟

1242. 修改数组 - AcWing题库

#include<iostream>
#include<algorithm>

using namespace std;
const int N=1e6+10;
   int n;
int p[N];

int find(int x)
{
    if(p[x]!=x) p[x]=find(p[x]);
    return p[x];
}
int main()
{

    cin>>n;
    //cout<<n<<endl;
    for(int i=1;i<=N;i++)
    {
        p[i]=i;  //1 2 3 4 5
    }
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d", &x);
        x=find(x);//找到x的归宿
        printf("%d ",x);
        p[x]=x+1;//下一次还是x的话,它的归宿就是x+1
    }
    return 0;
}