HDU 1029 Ignatius and the Princess IV 【桶 | 排序】

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1029
在这里插入图片描述
在这里插入图片描述
★这题我用的最机械(愚蠢 )的方法,一个装数字的桶,然而简单的方法也有awa,我用三种方法解决

翻译:

再次感谢 kuangbin的基础DP训练 中的翻译,但不知道这题跟DP啥关系233
在这里插入图片描述

思路:

方法一:通过一个桶(数组),若出现的数a,num[a]++;输入完后 循环一次,num[i]大于一半的输出即可,最常规思维。。。我也只有这个水平了
方法二:思考深入一点,如果有一个数大于一半了,排一次序之后,中间的肯定是 答案
方法三:在深入一点,既然大于一半了,出现一个数就count++,如果和这个数不相等就count–,count=0就换数,最后标记的一定是答案,因为他最终可以count+=(n+1)/2,排序也不需要了~

代码:

方法一:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e6+5;
int num[maxn];
int main()
{
    int n;
    while(cin>>n){
        memset(num,0,sizeof num);
        for(int i=1;i<=n;i++){
            int a;scanf("%d",&a);
            num[a]++;
        }
        for(int i=1;i<=1e6;i++){
            if(num[i]>=(n+1)>>1)
                cout<<i<<endl;
        }
    }
    return 0;
}

方法二:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+5;
int a[maxn];
int main()
{
    int n;
    while(cin>>n){
        for(int i=1;i<=n;i++) cin>>a[i];
        sort(a+1,a+n+1);
        cout<<a[(n+1)/2]<<endl;
    }
    return 0;
}

方法三:

#include <stdio.h>
#include <stdlib.h>
int main()
{
      int ans,num,count,n;
      while(scanf("%d",&n)!=EOF){
         count=0;
         for(int i=1;i<=n;i++){
            scanf("%d",&ans);
            if(count==0){
               num=ans;
               count ++;
            }
            else 
             if(ans==num) count++;
             else count--;
         }
         printf("%d\n",num);
      }
   return 0;   
}

时空比较如下,依次法一法二法三
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
还要加油鸭~

猜你喜欢

转载自blog.csdn.net/weixin_43890662/article/details/88620840
今日推荐