7-3 投票统计
分数 15
作者 TracyLi
单位 成都信息工程大学
用程序模拟一个活动的投票统计功能。首先输入参选人员个数,再输入每位参选人员名字(不超过20字节),再输入选票张数,再依次输入选票中所选的参选人名(选票中必须选参选中的其中一位)。在输入选票过程中统计每位参选人的得票数,最终按得票数由高到低的顺序输出参选人和其票数(空格分隔),如果票数相同,则按名字从小到大的顺序(ASCII码顺序)输出。
提示:选票信息按如下结构定义:

struct vote
{
char name[20];//名字
int count;//票数
};
输入样例:
3
Li
Wang
Zhang
8
Li
Wang
Li
Zhang
Li
Li
Wang
Zhang
输出样例:
Li 4
Wang 2
Zhang 2

#include #include #include struct Vote {char name[20];int count;};int compare_votes(const void *a, const void *b) {const struct Vote *vote_a = (const struct Vote *)a;const struct Vote *vote_b = (const struct Vote *)b;if (vote_a->count == vote_b->count) {return strcmp(vote_a->name, vote_b->name);}return vote_b->count - vote_a->count;}int main() {int num_candidates, num_votes;scanf("%d", &num_candidates);struct Vote *candidates = (struct Vote *)malloc(num_candidates * sizeof(struct Vote));for (int i = 0; i < num_candidates; i++) {scanf("%s", candidates[i].name);candidates[i].count = 0;}scanf("%d", &num_votes);for (int i = 0; i < num_votes; i++) {char selected_name[20];scanf("%s", selected_name);for (int j = 0; j < num_candidates; j++) {if (strcmp(selected_name, candidates[j].name) == 0) {candidates[j].count++;break;}}}qsort(candidates, num_candidates, sizeof(struct Vote), compare_votes);for (int i = 0; i < num_candidates; i++) {printf("%s %d\n", candidates[i].name, candidates[i].count);}free(candidates);return 0;}