Codeforces Round #315 (Div. 2B) 569B Inventory 贪心

本文针对一个特定的序列重构问题提供了解决方案。该问题要求在最少的修改下,将一个包含重复或非法数字的序列调整为包含1到n的所有整数的连续序列,并输出最终序列。采用贪心算法实现,通过标记数组记录各数值出现次数,找到缺失值并替换不合法或重复的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Click here

题意:给你n,然后n个数,n个数中可能重复,可能不是1到n中的数。然后你用最少的改变数,让这个序列包含1到n所有数,并输出最后的序列。

分析:贪心。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int M = 1e5+5;
 4 
 5 int n;
 6 int a[M];   // 给定序列
 7 int mark[M];    // mark[i] 表示i在给定序列中的出现次数
 8 int notap[M];   // 给的序列中没有出现的元素
 9 bool firstout;
10 
11 void print( int x ) {   // 输出格式控制 ps:在CF上测试了一下,不管这个格式也能AC
12     if( firstout )  {
13         printf("%d", x );
14         firstout = false;
15     }  
16     else
17         printf(" %d", x );
18 }
19 
20 int main()  {
21     while( ~scanf("%d", &n ) )  {
22         memset( mark, 0, sizeof(mark) );
23         memset( notap, 0, sizeof(notap) );
24         for( int i=1; i<=n; i++ )   {
25             scanf("%d", a+i );
26             mark[a[i]]++;
27         }
28         int cnt = 1;
29         for( int i=1; i<=n; i++ )
30             if( !mark[i] )  {
31                 notap[cnt] = i;
32                 cnt++;
33             }
34         firstout = true;
35         int top = 1;
36         for( int i=1; i<=n; i++ )
37             if( mark[a[i]] == 1 && a[i] <= n )  // 给定序列中有这个数并且范围合法
38                 print( a[i] );
39             else    {
40                 print( notap[top] );    // 不然从没有的序列中弹出一个数
41                 top++;
42                 mark[a[i]]--;
43             }
44         printf("\n");
45     }
46     return 0;
47 }

 

转载于:https://www.cnblogs.com/TaoTaoCome/p/4722294.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值