某校學生會主席選舉,有 m 位候選人(編號 1~m,0 < m < 1000),n 名學生投票(0 < n < 30000)。每人投一票,選一名候選人。統計得票最高的候選人編號及其得票數。
第一行:m n
第二行起:n 個整數,表示每位學生投票的候選人編號。
第一行:得票最多的候選人編號
第二行:該候選人得票數
3 10 1 2 3 2 3 1 2 3 1 3
3 4
經典的計數問題。開一個大小為 m+1 的陣列 cnt[],索引即候選人編號,遍歷所有選票累加計數,最後掃描陣列找最大值及其索引。
#include <stdio.h>
int main() {
int m, n;
scanf("%d %d", &m, &n);
int cnt[1001] = {0};
for (int i = 0; i < n; i++) {
int k; scanf("%d", &k);
if (k >= 1 && k <= m) cnt[k]++;
}
int max_votes = 0, winner = 0;
for (int i = 1; i <= m; i++) {
if (cnt[i] > max_votes) {
max_votes = cnt[i];
winner = i;
}
}
printf("%d\n%d\n", winner, max_votes);
return 0;
}
n ≤ 30000,m ≤ 1000,極快。m+1 方便直接用編號做索引。scanf 循環讀取 n 次即可自動跨行。