Ignatius and the Princess IV(暴力)

来源:互联网 发布:长春淘宝客服挣钱么 编辑:程序博客网 时间:2024/05/29 06:31
"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
51 3 2 3 3111 1 1 1 1 5 5 5 5 5 571 1 1 1 1 1 1
Sample Output
351
题意:

在N个数字中,找到出现次数大于(N+1)/2的数字,N为奇数

思路:

由于题目保证这个数字一定出现,所以每个数字出现的次数记录下来,找到最大的

代码:

#include<stdio.h>#include<algorithm>#include<string.h>.using namespace std;int book[1000000];//记录数字在num数组的位置,如果没出现则为-1struct node{    int num;//存数字    int ans;//存该数字的出现次数}dp[1000000];int cmp(node a,node b){    return a.ans>b.ans;}int n;int main(){    while(scanf("%d",&n)!=EOF){        memset(book,-1,sizeof(book));        memset(dp,0,sizeof(dp));        int m=(n+1)/2;        int cnt=0;        int i;        for(i=0;i<n;i++){            int a;            scanf("%d",&a);            if(book[a]==-1){//没出现过                book[a]=cnt;                dp[cnt].num=a;                dp[cnt++].ans++;            }            else{//出现过,找到在num数组的位置                int b=book[a];                dp[b].ans++;            }        }        sort(dp,dp+cnt,cmp);        for(i=0;i<cnt;i++)         printf("%d\n",dp[0].num);    }return 0;}



原创粉丝点击