洛谷刷题笔记Q1 宇宙总统

题目链接

宇宙总统

题目描述

地球历公元 6036 年,全宇宙准备竞选一个最贤能的人当总统,共有 n n n 个非凡拔尖的人竞选总统,现在票数已经统计完毕,请你算出谁能够当上总统。

输入格式

第一行为一个整数 n n n,代表竞选总统的人数。

接下来有 n n n 行,分别为第一个候选人到第 n n n 个候选人的票数。

输出格式

共两行,第一行是一个整数 m m m,为当上总统的人的号数。

第二行是当上总统的人的选票。

样例 #1

样例输入 #1

5
98765
12365
87954
1022356
985678

样例输出 #1

4
1022356

提示

票数可能会很大,可能会到 100 100 100 位数字。

1 ≤ n ≤ 20 1 \leq n \leq 20 1n20

思考

此题的难点在于票数可能会很大,可能会到 100 位数字,是一个正常的数据类型没法存储的,因此只能考虑string类型先存储。

先不考虑票数非常大,用long long存票数

代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct president{
    int vote;//投票数
    long long order;//号数

    bool operator<(const president& other)const{
        return vote>other.vote;
    }
};

int main(){
    //freopen("a.in","r",stdin);
    int n;
    cin>>n;
    vector<president> a;
    president tmp;
    for(int i=0;i<n;i++){
        cin>>tmp.vote;
        tmp.order=i+1;
        a.push_back(tmp);
    }
    sort(a.begin(),a.end());
    cout<<a[0].order<<endl;
    cout<<a[0].vote<<endl;
    return 0;
}

考虑票数可能达到100位

由于本题的票数可能达到100位,超出long long的存储极限,因此使用字符串(string)类型来存储可能有100位数字的投票数。需要更改operator<的判断条件。
代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct president{
    string vote;//投票数
    int order;//号数

    bool operator<(const president& other)const{
        if(vote.size()==other.vote.size()){
            for(int i=0,num=vote.size();i<num;i++){
                if(vote[i]!=other.vote[i])
                    return vote[i]>other.vote[i];
                if(i==num-1)//如果比到最后一位还是一样的,那么随便返回false还是true都行
                    return false;
            }
        }
        else return vote.size()>other.vote.size();
    }
};

int main(){
    freopen("a.in","r",stdin);
    int n;
    cin>>n;
    vector<president> a;
    president tmp;
    for(int i=0;i<n;i++){
        cin>>tmp.vote;
        tmp.order=i+1;
        a.push_back(tmp);
    }
    sort(a.begin(),a.end());
    cout<<a[0].order<<endl;
    cout<<a[0].vote<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值