Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the items are not numbered sequentially, and some items even share the same inventory number! There is an urgent need to fix it. You have chosen to make the numbers of the items sequential, starting with 1. Changing a number is quite a time-consuming process, and you would like to make maximum use of the current numbering.
You have been given information on current inventory numbers for n items in the company. Renumber items so that their inventory numbers form a permutation of numbers from 1 to n by changing the number of as few items as possible. Let us remind you that a set of n numbers forms a permutation if all the numbers are in the range from 1 to n, and no two numbers are equal.
The first line contains a single integer n — the number of items (1 ≤ n ≤ 105).
The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 105) — the initial inventory numbers of the items.
Print n numbers — the final inventory numbers of the items in the order they occur in the input. If there are multiple possible answers, you may print any of them.
3 1 3 2
1 3 2
4 2 2 3 3
2 1 3 4
1 2
1
In the first test the numeration is already a permutation, so there is no need to change anything.
In the second test there are two pairs of equal numbers, in each pair you need to replace one number.
In the third test you need to replace 2 by 1, as the numbering should start from one.
题意:给出一个数字n,接下来是n个数,把其中的重复的数或者大于n的数进行替换,使得整个数列是由1~n来组成的,可能会有
多种答案,输出其中任意一种。
思路:把数列的值和次序存入结构体数组ch中,同时用vis数组记录1~n中数的出现次数。接着从1遍历到n,如果vis[i] == 0(1 <=
i <= n)。那么j从1遍历到n找ch[j].value > n || vis[ch[j].value]>1的,把ch[j].value替换为i,但这样做会超时,所以我们可以定义
一个jj来记录上次发现vis[i] == 0之后遍历到的j的位置。
代码如下
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
struct node
{
int value;
int id;
}ch[100000+10];
bool cmp1(node a,node b)
{
return a.value<b.value;
}
bool cmp2(node a,node b)
{
return a.id<b.id;
}
int vis[100000+10];
int main()
{
int n,jj;
while(~scanf("%d",&n)) {
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++) {
scanf("%d",&ch[i].value);
vis[ch[i].value]++;
ch[i].id=i;
}
ch[0].value=0,jj=0;
sort(ch+1,ch+n+1,cmp1);
for(int i=1;i<=n;i++) {
if(!vis[i]) {
for(int j=jj;j<=n;j++) {
if(ch[j].value>n||vis[ch[j].value]>1) {
vis[ch[j].value]--;
ch[j].value=i;
vis[i]=1;
jj=j;
break;
}
}
}
}
sort(ch+1,ch+n+1,cmp2);
for(int i=1;i<=n;i++) {
if(i!=n)
printf("%d ",ch[i].value);
else
printf("%d\n",ch[i].value);
}
}
return 0;
}