IgnaTIus and the Princess IV
describe
“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.
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 1Sample Output
3 5 1此题让求奇数个数中出现次数超过总数一半的数,容易超时超内存,这里使用一种比较简单的算法。首先要知道,在所有数中,去除两个不同的数对结果没有影响,利用这一点我们可以先记录第一次输入的数,如果和下一次输入的数相同,计数器加一,否则减一(即去除两个不同数);当计数器为零时,这个数被全部去除,然后再记录下一次输入的数,重复上述 *** 作。当输入全部数之后,所留下的记录的数就是答案。
#include<cstdio> int main() { int n,t,res,cnt=0,i; while(scanf("%d",&n)!=EOF) { scanf("%d",&t); res=t; cnt=1; for(i=1;i<n;i++) { scanf("%d",&t); if(res==t) cnt++; else cnt--; if(cnt==0) { res=t; cnt=1; } } printf("%d\n",res); } return 0; }欢迎分享,转载请注明来源:内存溢出
评论列表(0条)