hdu 1029

 1 #include"stdio.h"
 2 int main(void)
 3 {
 4     int n,x,y,t,i;
 5     while(scanf("%d",&n)!=EOF)
 6     {
 7         scanf("%d",&x);
 8         t=1;
 9  
10         for(i=1;i<n;i++)
11         {
12             scanf("%d",&y);
13             if(y==x)    t++;
14             else 
15                 if(t==0)    x=y;
16                 else t--;    
17         }
18         printf("%d\n",x);    
19     }
20     return 0;
21 }
Problem 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

其实最开始我选择用一个 500000 的数组,后来编译器玩不转我就放弃了,记得以前看到过一段最大子串和的代码,作者就用子串和与零的关系AC,觉得应该有戏,就朝着这方面分析。

问题的在于出现至少(N+1)/2 次的那个整数是多少?(注意(N+1)/2占据数列的一半多的数目)假设是 x ,对于该数列而言存在两种数:x,非x;x至少有(N+1)/2 个数,非x数少于有 (N+1)/2 个数,用H表示x的数目,Hh表示非x的数目,H-Hh>0;根据这个我们可以衍生这种想法:每一个x消耗一个非x,剩余的数肯定就是目标数。这一过程算法的实现就是代码7--17.

7-8是接收第一个数,作为比较的开始;    10--17就是在消耗非x数,如果新的到的数是x,t++,相反不是t--,这样就实现了对非x的消耗,就像这个数列只有1和2,如果得到1,我就t++,如果得到2,我就t--,如果t<=0了,那么我就让比较值为2,下一个数是2,t++,否则t--,相当于1和2在相互消耗,剩余的那个肯定就是数目最多的那个。

  通过这个问题,我们应该思考算法最本质的东西,有很多种算法可以用,它们都是由前辈高手总结归纳或则研究出来的,对于不同的问题有着不同的策略,如果直接输出“Hello World”都要用算法解决,那就真的没意义了。对于不同的问题,会不会先尝试着建立数学模型,再想法转化为算法模型,(数学很重要呀),解决问题的思路各有不同,虽然可能代码相似,长期坚持,希望我能成为一个电脑高手!!

如果哪里有不对的地方希望大家能告诉我,向您学习。真心谢谢!

posted @ 2016-05-18 23:39  DoubleLeft  阅读(340)  评论(0编辑  收藏  举报