最小序列(min.cpp)—CF1506D—1400
时间限制 2s | 空间限制 256M
题目描述:
现有一个长度为 n 的序列 a ,你可以对其进行如下操作:选择 i , j 满足 ai≠aj ,然后删除 ai , aj 两个数。求序列 a 经过若干次操作后,最少有几个数。
输入格式:
输入的第一行包含一个整数 t(1<=t<=10^4)——测试中的测试用例数量。
以下是每个测试用例的描述。
每个测试用例的第一行包含一个整数 n(1<=n<=2*10^5)——序列 a 的长度。
每个测试用例的第二行有 n 个正整数 a1,a2,…,an ( 1<=ai<=10^9) 。
其中所有测试数据中 n 的和<=2*10^5
输出格式:
共有 t 行,依次对应 t 组测试数据的结果。
对于每组数据,输出一个整数,表示经过操作后,序列中最少有几个数。
样例输入输出:
样例1输入 | 样例1输出 |
---|---|
5 6 1 6 1 1 4 4 2 1 2 2 1 1 5 4 5 4 5 4 6 2 3 2 1 3 1 | 0 0 2 1 0 |
题解:
首先找规律,发现影响答案的只会是出现最多的数的出现次数。
用 maxn 表示出现次数最多的数的出现次数。
只有当 n 为奇数且 maxn<=n/2时序列剩下一个数
其余情况则为 max(maxn*2-n,0) 。
参考代码:
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int a[N];
int main()
{
ios::sync_with_stdio(0);
int t;
cin>>t;
while(t--)
{
int n,maxn=0;
cin>>n;
map<int,int>cnt;
memset(a,0,sizeof(a));
for(int i=1;i<=n;i++)
{
cin>>a[i];
cnt[a[i]]++;
}
for(int i=1;i<=n;i++)
maxn=max(maxn,cnt[a[i]]);
if(n%2==1&&maxn<=n/2)
cout<<1<<endl;
else
cout<<max(maxn*2-n,0)<<endl;
}
return 0;
}