Ignatius and the Princess IV
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32767 K (Java/Others)
Total Submission(s): 30075 Accepted Submission(s):
12837
"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?
我们按照序列依次扫描,先把第一个x的值给flag
计数器num++ 然后向右扫描
如果输入的x跟flag相同 那num就++,不同,就 --,
一直重复下去,到了最后flag就是我们想要的那个多元素。
下面是代码:
#include <stdlib.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
while(~scanf("%d",&n))
{
int num=0,flag,x;
for(int i=0;i<n;i++)
{
scanf("%d",&x);
if(num==0)
{
num++;
flag=x;
}
else if(flag==x)
{
num++;
}
else
{
num--;
}
}
printf("%d
",flag);
}
return 0;
}