B - Ignatius and the Princess IV

B - Ignatius and the Princess IV

题目入口:B - Ignatius and the Princess IV
杭电入口:Ignatius and the Princess IV

解题思路

题目:给一列数,找出出现(n+1)/2次的数字
第二个代码为直接模拟 过掉不说
第一个代码的巧妙之处
设一个标志 通过输入更新标志 如果输入的数和前边的数不同就–cnt 否则++cnt
如果cnt<=0了就更新标志
因为给的是奇数 所以总有一个数会出现会多一次 所以不用担心会出现别的情况
如果解释的不够清楚
我们再来看下这一段话
(引自)https://www.cnblogs.com/kuangbin/archive/2011/07/30/2122217.html
多元素即在数列中出现次数多于n/2的元素
我们很容易的看出来 在一个序列中如果去掉2个不同的元素
那么原序列中的多元素 在新的序列中还是多元素
到这里还不太清楚我就再说的明白一点
现在有一个士兵大战
给定11个数的士兵 考虑最坏的情况是最多元素的士兵有6个 其他元素的士兵有5个来满足题意
用其他的元素士兵去和最多元素士兵一一同归于尽 最后会剩下1个最多元素的士兵
那么显然其他情况最多元素的剩余士兵更多
到这里讲解结束

AC代码

#include <iostream>
#include <cstring>
using namespace std;
int main(){
    int n, tmp, ret = 0;
    while (~scanf("%d", &n)){
        int cnt = 0;
        while (n--){
            scanf("%d", &tmp);
            if (cnt <= 0) ret = tmp;
            tmp == ret ? ++cnt : --cnt;
        }
        printf("%d\n", ret);
    }
    return 0;
}

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
int a[1000010];
int main() {
    int n;
    while (~scanf("%d", &n)){
        memset(a, 0, sizeof(a));
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);
        sort(a, a + n);
        int tmp = a[0];
        int cnt = 1;
        for (int i = 1; i < n; i++){
            if (a[i] == tmp){
                cnt++;
                if (cnt >= (n+1)/2){
                    printf("%d\n", a[i]);
                    break;
                }
            }
            else {
                tmp = a[i];
                cnt = 1;
            }
        }
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值