P9421 [蓝桥杯 2023 国 B] 班级活动 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
分析
题意弄清楚了挺简单的~(最开始以为是只有两个配对就行。。。)
题目要求的是与 i 对应的是唯一的 j
思路:
用id作为数组a[]下标,记录其出现的个数,分情况讨论:
1.当a[id] == 2,符合条件,无需改变
2.当a[id] > 2,需要改变的个数是a[id] - 2个
3.当a[id] == 1,需要改变的个数是1个
情况2.3是一样的,但是对于2而言,只要>2,超出的部分必须都要修改;对于情况3,可以只修改一半的数量,如:1 2 2 2 2 3,a[4]、a[5]必须都要修改(因为对于2而言,已经有一对id=2出现了);a[1]、a[6]可以将其中一个改为另一个即可,不用两个都修改
对于上述例子,最少改变次数就是将两个2分别改成1和3
总结:
当情况3的个数 > 情况2的个数,cnt += (情况3-情况2)/2+情况2
当情况3的个数 <= 情况2的个数,cnt = 情况2的个数
代码
#include<iostream>
using namespace std;
const int N = 100010;
int a[N],n;
bool b[N];
int main()
{
scanf("%d",&n);
int maxx = 0;
for(int i = 1;i <= n;i ++)
{
int id;
scanf("%d",&id);
maxx = max(maxx,id);
a[id] ++;
}
int cnt = 0;
int res1 = 0;
int res2 = 0;
for(int i = 1;i <= maxx;i ++)
{
if(a[i] == 1) res1 ++;
if(a[i] > 2) res2 += a[i] - 2;
}
if(res1 > res2)
{
cnt += res2;
cnt += ((res1-res2)/2);
}
else if(res1 <= res2)
{
cnt = res2;
}
printf("%d",cnt);
return 0;
}