zoukankan      html  css  js  c++  java
  • 【HDU

    Ignatius and the Princess IV 

    先搬中文

    Descriptions:
     
    给你n个数字,你需要找出出现至少(n+1)/2次的数字 现在需要你找出这个数字是多少?
    Input

    本题包含多组数据,请处理到EOF: 每组数据包含两行。 第一行一个数字N(1<=N<=999999) ,保证N为奇数。 第二行为N个用空格隔开的整数。

    Output

    对于每组数据,输出一行,表示要求找到的那个数

    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

    题目链接:

    https://vjudge.net/problem/HDU-1029

    找出数列里面出现次数多于n/2的的元素

    既然次数大于n/2,那么例如3、2、3、1、3、2、3

    1. 去掉3    2
    2. 去掉3    2
    3. 去掉3    1
    4. 还剩一个3

    由此可得我们按照序列一次扫描,把第一个数字x赋值给ans,计数器cnt=0

    若是后来数字x与ans相同,则cnt++,否则cnt-- 若cnt为0,则重新找(不用倒回开头)以此循即可

    AC代码

    #include <bits/stdc++.h>
    #define Mod 1000000007
    #define eps 1e-6
    #define ll long long
    #define INF 0x3f3f3f3f
    #define MEM(x, y) memset(x, y, sizeof(x))
    #define Maxn 1000
    using namespace std;
    int main()
    {
        int n,x,ans,cnt;
        while(cin>>n)
        {
            cnt=0;
            for(int i=0; i<n; i++)//存数
            {
                cin>>x;
                if(cnt==0)//计数器为0,重新计数
                {
                    ans=x;
                    cnt=1;
                }
                else
                {
                    if(ans==x)//相同,计数器+1
                        cnt++;
                    else//不同-1
                        cnt--;
                }
            }
            cout<<ans<<endl;
        }
        return 0;
    }
     
  • 相关阅读:
    vue-router 滚动行为封装示例
    HTML5 History 模式 后端ngnix配置
    vue-router 嵌套命名视图
    npm 源管理 nrm
    windows系统git使用zip命令报错解决方法
    vue v-html 动态内容样式无效解决方法
    vue 项目打包 本地预览
    Vue 项目环境变量
    Oracle中的统计信息
    宽表和窄表的区别---字段
  • 原文地址:https://www.cnblogs.com/sky-stars/p/12367539.html
Copyright © 2011-2022 走看看