题目链接
1242. 修改数组
给定一个长度为 $N$ 的数组 $A=[A_1,A_2,⋅⋅⋅A_N]$,数组中有可能有重复出现的整数。
现在小明要按以下方法将其修改为没有重复整数的数组。
小明会依次修改 $A_2,A_3,⋅⋅⋅,A_N$。
当修改 $A_i$ 时,小明会检查 $A_i$ 是否在 $A_1∼A_i−1$ 中出现过。
如果出现过,则小明会给 $A_i$ 加上 $1$;如果新的 $A_i$ 仍在之前出现过,小明会持续给 $A_i$ 加 $1$,直到 $A_i$ 没有在 $A_1∼A_i−1$ 中出现过。
当 $A_N$ 也经过上述修改之后,显然 $A$ 数组中就没有重复的整数了。
现在给定初始的 $A$ 数组,请你计算出最终的 $A$ 数组。
输入格式
第一行包含一个整数 $N$。
第二行包含 $N$ 个整数 $A_1,A_2,⋅⋅⋅,A_N$。
输出格式
输出 $N$ 个整数,依次是最终的 $A_1,A_2,⋅⋅⋅,A_N$。
数据范围
$1≤N≤10^5,$
$1≤A_i≤10^6$
输入样例:
5
2 1 1 3 4
输出样例:
2 1 3 4 5
解题思路
单链表式并查集
即原来的并查集是棵树,现在变成一个单链表的形式,当某个点 $x$ 用过时,其父节点指向 $x+1$
- 时间复杂度:$O(n)$
代码
// Problem: 修改数组
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1244/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
// %%%Skyqwq
#include <bits/stdc++.h>
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
template <typename T> void inline read(T &x) {
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
x *= f;
}
const int N=1100005;
int n,fa[N];
int find(int x)
{
return fa[x]==x?x:fa[x]=find(fa[x]);
}
int main()
{
for(int i=1;i<N;i++)fa[i]=i;
cin>>n;
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
x=find(x);
cout<<x<<' ';
fa[x]=x+1;
}
return 0;
}