Ignatius and the Princess IV HDU - 1029

原题链接

考察:思维 or STL

思路一:

       map记录出现次数.(说是这么说,但我看此题的第一反应是离散化)

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <unordered_map>
 5 using namespace std;
 6 const int N = 1000010;
 7 unordered_map<int,int> um;
 8 int n;
 9 int main() 
10 {
11     while(scanf("%d",&n)!=EOF)
12     {
13         int x;
14         um.clear();
15         for(int i=1;i<=n;i++)
16         {
17             scanf("%d",&x);
18             um[x]++;
19         }
20         for(auto it:um) 
21           if(it.second>=(n+1>>1))
22           {
23                printf("%d\n",it.first);
24                break;
25           }
26     }
27     return 0;
28 }
思路一

 

思路二:

       用dp的思想,将大问题分解为多个小问题,当N = 5,ans出现3次,其余2个是多余的数,再将问题细化,当N = 3,ans出现2次,其余出现1次.当N = 1,此数一定是ans.

       当我们得到一个数字,假设为ans.当下一个数字不同,ans出现次数-1,当ans==0,说明此数字不是ans.再设当前遍历数字为ans.

 1 #include <iostream>
 2 using namespace std;
 3 const int N = 1000010;
 4 int a[N],n;
 5 int main()
 6 {
 7     while(scanf("%d",&n)!=EOF)
 8     {
 9         for(int i=1;i<=n;i++) scanf("%d",&a[i]);
10         int cnt = 0,ans,i = 1;
11         while(i<=n)
12         {
13             if(!cnt) ans = a[i],cnt++;
14             else if(ans==a[i]) cnt++;
15             else if(ans!=a[i]) cnt--;
16             i++;
17         }
18         printf("%d\n",ans);
19     }
20     return 0;
21 }

 

posted @ 2021-03-13 14:39  acmloser  阅读(50)  评论(0编辑  收藏  举报