HDU 1029 Ignatius and the Princess IV DP

kuangbin 专题

这题,有很多种解法。

第一种:

直接比较每个数出现次数。

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<cstdio>
 6 #include<set>
 7 #include<map>
 8 #include<vector>
 9 #include<cstring>
10 #include<stack>
11 #include<cmath>
12 #include<queue>
13 #include <bits/stdc++.h>
14 using namespace std;
15 #define INF 0x3f3f3f3f
16 #define LL long long
17 #define clc(a,b) memset(a,b,sizeof(a))
18 const int maxn=1000000;
19 int a[maxn];
20 int b[maxn];
21 int main()
22 {
23     int n;
24 
25     while(~scanf("%d",&n))
26     {
27         clc(b,0);
28         for(int i=0;i<n;i++)
29         {
30             scanf("%d",&a[i]);
31             b[a[i]]++;
32         }
33         int maxx=-1;
34         int ans;
35         for(int i=0;i<10000;i++)
36         {
37             if(maxx<b[i])
38                 {
39                     maxx=b[i];
40                     ans=i;
41                 }
42         }
43         printf("%d\n",ans);
44     }
45     return 0;
46 }
View Code

第二种:

应为输出至少(n+1)/2次的数,所以,最后result一定是要求的数。

 1 #include<iostream>
 2 #include<string>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<cstdio>
 6 #include<set>
 7 #include<map>
 8 #include<vector>
 9 #include<cstring>
10 #include<stack>
11 #include<cmath>
12 #include<queue>
13 #include <bits/stdc++.h>
14 using namespace std;
15 #define INF 0x3f3f3f3f
16 #define LL long long
17 #define clc(a,b) memset(a,b,sizeof(a))
18 const int maxn=1000000;
19 int a[maxn];
20 int b[maxn];
21 int main()
22 {
23     int n,i;
24     int t;
25     int cnt;
26     int result;
27     while(scanf("%d",&n)!=EOF)
28     {
29         cnt=0;
30         for(i=0; i<n; i++)
31         {
32             scanf("%d",&t);
33             if(cnt==0)
34             {
35                 cnt=1;
36                 result=t;
37             }
38             else
39             {
40                 if(t==result)cnt++;
41                 else cnt--;
42             }
43         }
44         printf("%d\n",result);
45     }
46     return 0;
47 }
View Code

 

posted @ 2016-01-18 00:38  yyblues  阅读(169)  评论(0编辑  收藏  举报