码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1029 简单DP

时间:2020-02-02 13:45:34      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:tput   情况   time   next   ase   size   假设   lines   out   

"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?

InputThe 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.
OutputFor 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
题意是给一个项数为奇数的数列,里面有一个元素出现次数大于(n+1)/2次,找出这个数。
因为要求的这个数一定大于这个数列个数的一半,所以不妨假设拿每次都取这个数和其他的数一换一,最终剩下的还是这个数。最坏情况是这个出现次数最多的数出现了(n+1)/2次,经过了(n-1)/2次相消后剩下一个这个数,其他情况例如拿其他的不同的数相消,最后剩下的数也一定是出现次数最多的数且剩下的数量大于1。代码也就呼之欲出了。
#include <bits/stdc++.h>
using namespace std;
int n;
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        int i;
        int num=-1;//存储出现次数最多的数 
        int cnt=0;//num出现的次数, 
        int pre;//之前的数 
        for(i=1;i<=n;i++)
        {
            int temp;
            scanf("%d",&temp);
            if(i==1)
            {
                num=temp;
                pre=temp;
                cnt++;
                continue;
            }
            if(temp==pre)cnt++;//输入的数与pre相同时 累计次数++ 
            else
            {
                if(pre==-1)//重置 
                {
                    num=temp;
                    pre=temp;
                    cnt=1;
                    continue;
                }
                cnt--;//没有两两抵消掉且当前输入数与pre不同,累计次数-- 
                if(cnt==0)pre=-1;//如果之前所有数都两两抵消掉了,即累计次数为0,就重置 
            }
        }    
        cout<<num<<endl;
    }    
}

 

HDU1029 简单DP

标签:tput   情况   time   next   ase   size   假设   lines   out   

原文地址:https://www.cnblogs.com/lipoicyclic/p/12251848.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!