HDU--1029 Ignatius and the Princess IV (map&&思维&&memset)

来源:互联网 发布:淘宝转化率 编辑:程序博客网 时间:2024/06/07 16:13

Ignatius and the Princess IV

 

"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

解题思路:这道题就是让求所给出的数组中相同数字个数超过n/2的数字。其实这道题有多种解法,在下面一一列出。

1.利用map,用map<int,int> d;用数组d[t]计数,使用for循环,直至找到d[t] > n/2.代码如下:

#include<cstdio>#include<map>#include<algorithm>using namespace std;int main(){int n;while (~scanf ("%d",&n) && n){map<int,int> d;//定义一个新的数组来记录一个数出现的次数;int ans;for (int i = 1 ; i <= n ;i++){int t;scanf ("%d",&t);d[t]++;if (d[t] > n/2)ans = t;}printf ("%d\n",ans);}return 0;}


2.这道题如果多想想,用思维解决就更简单了。因为数组是奇数数组,要想满足至少有(N+1)/2个数相同,若存在,不管怎样,将数组从小到大排序后第(N+1)/2个数一定是所要寻找的数字。所以可以直接将数组进行排序,输出第(N+1)/2个数就可以了。

#include<stdio.h>#include<algorithm>using namespace std;const int maxn=1000005;int m[maxn];int main(){int n;while(scanf("%d",&n)!=EOF){for(int i=0;i<n;i++){scanf("%d",&m[i]);}sort(m,m+n);//使用sort快速排序,默认从小到大排序;printf("%d\n",m[(n+1)/2]);直接输出排好序的第(n+1)/2个数;}return 0; } 

3.使用memset清空数组,也是用一个数组m[maxn]记数。

#include<stdio.h>#include<iostream>#include<string.h>const int maxn=1000005;int m[maxn];int main(){int n,num,s;while(scanf("%d",&n)!=EOF){memset(m,0,sizeof(m));for(int i=1;i<=n;i++){scanf("%d",&num);m[num]++;if(m[num]>n/2){s=num;}}printf("%d\n",s);}return 0;}