[HDU1029]Ignatius and the Princess IV<桶 水题>

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1029

题目大意:

多组数据,每组数据先给一个n,然后给n各数字,找出n各数字中出现了至少(n+1)/2次的数字并输出(保证n为奇数)

看到这题被分类进了dp我还是有点懵逼,我不知道我这算不算dp做法。

我是用的桶排序思想,

由于数据范围如此,直接进行遍历桶是会炸时间的,

所以多开一个数组记录下出现过的数字就行。

题不难

#include<cstdio>
#include<cstring> 
#include<iostream>
using namespace std;

int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int barrel[1000005],n,have[1000005],tot;

int main(){
    while(scanf("%d",&n)!=EOF){
        tot=0;memset(barrel,0,sizeof(barrel));
        for(int i=1;i<=n;i++){
            int a=read();
            if(barrel[a]==0)have[++tot]=a;
            barrel[a]++;
        }
        int num=(n+1)/2;
        for(int i=1;i<=tot;i++)
            if(barrel[have[i]]>=num){
                cout<<have[i]<<endl;break;
            }
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/Danzel-Aria233/p/12292580.html