宇宙总统
题目描述
地球历公元 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 1≤n≤20
思考
此题的难点在于票数可能会很大,可能会到 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;
}