HDU 1029 Ignatius and the Princess IV (思维题,排序?)
Description
"OK, you are not too bad, em... But you can never pass the next test." feng5166 says.
"I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers." feng5166 says.
"But what is the characteristic of the special integer?" Ignatius asks.
"The integer will appear at least (N+1)/2 times. If you can't find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha....." feng5166 says.
Can you find the special integer for Ignatius?
Input
The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.
Output
For each test case, you have to output only one line which contains the special number you have found.
Sample Input
5
1 3 2 3 3
11
1 1 1 1 1 5 5 5 5 5 5
7
1 1 1 1 1 1 1
Sample Output
3
5
1
Http
https://vjudge.net/problem/HDU-1029
Source
思维题,排序?
题目大意
给一个保证个数n为奇数个的数列,求里面那个出现了至少n/2+1次的数
解决思路
因为我们要输出的数出现了至少n/2+1次,所以我们用一个cnt记录当前某个数的出现次数(看不懂?没关系,往下看)。每读入一个数,我们看一下当前的cnt是否是0,如果是0,则把Ans更新为当前读入的数并把cnt置为1,否则,如果Ans与当前读入的数相同,则cnt+1,否则-1。
这个算法的正确性在于因为我们要输出的Ans的次数是大于等于n/2+1的,也就是说它出现的次数是大于其他所有数出现次数之和的。所以我们利用上面的方法,可以保证最后cnt记录的就是Ans。
另:强烈建议本题扩大数据范围,因为这题还可以用sort水过。因为要输出的数出现了至少n/2+1次,所以只要把所有的数排一边序,可以保证第n/2+1个数就是答案。
2017.8.26 Update
原代码在BZOJ上会MLE,原因是使用了std。请看最简化版
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n;
while (cin>>n)
{
int cnt=0,Ans=0;
for (int i=1;i<=n;i++)
{
int number;
scanf("%d",&number);
if (cnt==0)
{
cnt=1;
Ans=number;
continue;
}
if (number==Ans)
cnt++;
else
cnt--;
}
printf("%d\n",Ans);
}
return 0;
}
最简化版
#include<cstdio>
int main()
{
int n;
scanf("%d",&n);
int cnt=0,Ans=0;
for (int i=1;i<=n;i++)
{
int number;
scanf("%d",&number);
if (cnt==0)
{
cnt=1;
Ans=number;
continue;
}
if (number==Ans)
cnt++;
else
cnt--;
}
printf("%d\n",Ans);
return 0;
}
sort暴力方法:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxN=1000000;
const int inf=2147483647;
int n;
int Arr[maxN];
int main()
{
while (cin>>n)
{
for (int i=1;i<=n;i++)
scanf("%d",&Arr[i]);
sort(&Arr[1],&Arr[n+1]);
printf("%d\n",Arr[n/2+1]);
}
return 0;
}
为什么这题会出现在[kuangbin带你飞]的专题十二 基础DP1里?很迷……