把票数当字符串比较,先比长度,长度相同再按字典序比较大小。
OJ: luogu
题目 ID: P1781
难度:入门
标签:高精度字符串python
日期: 2026-07-15 22:18
题意
有 n 个候选人,每人的票数可能长达 100 位。输出票数最大的候选人编号和票数。
思路
票数很大,可以把它当字符串比较:
- 位数更多的票数一定更大;
- 位数相同,按字符串字典序比较即可。
扫描所有候选人,维护当前最大票数字符串和编号。
Python 知识
/home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:长数字可以先作为字符串读取。/home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:Python 也能用大整数,但字符串比较能直接体现高精度比较规则。len(votes)比较位数。- 字符串长度相同且只含数字时,字典序与数值大小一致。
代码
python
n = int(input())
best_index = 1
best_votes = input().strip()
for index in range(2, n + 1):
votes = input().strip()
if len(votes) > len(best_votes) or (
len(votes) == len(best_votes) and votes > best_votes
):
best_index = index
best_votes = votes
print(best_index)
print(best_votes)cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-07-27 00:00
* update_at: 2026-07-27 00:00
*/
#include <bits/stdc++.h>
using namespace std;
// 比较两个数字字符串:如果 s1 > s2 返回 true
bool bigger(const char *s1, const char *s2) {
int len1 = strlen(s1);
int len2 = strlen(s2);
if (len1 != len2) return len1 > len2; // 位数多的更大
return strcmp(s1, s2) > 0; // 位数相同,字典序比较
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int best_idx = 1;
char best[105];
cin >> best; // 读入第 1 个人的票数
for (int i = 2; i <= n; i++) {
char cur[105];
cin >> cur;
if (bigger(cur, best)) {
best_idx = i;
strcpy(best, cur);
}
}
cout << best_idx << "\n";
cout << best << "\n";
return 0;
}Pythonic 写法
元组比较选票:
python
n = int(input())
best_index, best_votes = 1, input().strip()
for index in range(2, n + 1):
votes = input().strip()
if (len(votes), votes) > (len(best_votes), best_votes):
best_index, best_votes = index, votes
print(best_index)
print(best_votes)复杂度
候选人数最多 20,票数字符串长度最多 100。时间复杂度
总结
高精度比较不一定要转成整数。对于非负整数字符串,先比长度,再比字典序,就是手写高精度比较的核心。