题目背景
宇宙总统竞选
题目描述
地球历公元6036年,全宇宙准备竞选一个最贤能的人当总统,共有n个非凡拔尖的人竞选总统,现在票数已经统计完毕,请你算出谁能够当上总统。
输入输出格式
输入格式:
president.in
第一行为一个整数n,代表竞选总统的人数。
接下来有n行,分别为第一个候选人到第n个候选人的票数。
输出格式:
president.out
共两行,第一行是一个整数m,为当上总统的人的号数。
第二行是当上总统的人的选票。
输入输出样例
输入样例#1: 复制
5
98765
12365
87954
1022356
985678
输出样例#1: 复制
4
1022356
说明
票数可能会很大,可能会到100位数字。
n<=20
题解
因为数据可能会到100位,所以应该用字符串处理,利用sort函数将最大票数找出。
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std;
struct president{
string s;
int number;
int length;
}a[21];
int cmp(president a, president b)
{
if(a.length == b.length){//长度相等,比较字符串大小
return a.s > b.s;
}
else{//长度不等,比较长度大小
return a.length > b.length;
}
}
int main()
{
int n;
cin >> n;
int i;
for(i = 0; i < n; i++){
cin >> a[i].s;
a[i].length = a[i].s.length();//记录长度
a[i].number = i + 1;//记录编号
}
sort(a, a + n, cmp);
cout << a[0].number << endl;
cout << a[0].s << endl;
return 0;
}
本文介绍了一个基于字符串处理的算法,用于解决宇宙总统竞选的问题。该算法通过读取候选人票数并使用sort函数按票数大小排序,最终输出获得最多票数的候选人及其票数。
294

被折叠的 条评论
为什么被折叠?



