HJ94. 记票统计
描述
输入描述
第一行输入候选人的人数n,第二行输入n个候选人的名字(均为大写字母的字符串),第三行输入投票人的人数,第四行输入投票。
输出描述
按照输入的顺序,每行输出候选人的名字和得票数量(以" : "隔开,注:英文冒号左右两边都有一个空格!),最后一行输出不合法的票数,格式为"Invalid : "+不合法的票数。
示例1
输入:
4 A B C D 8 A D E CF A GG A B
输出:
A : 3 B : 1 C : 0 D : 1 Invalid : 3
说明:
E CF GG三张票是无效的,所以Invalid的数量是3.C 解法, 执行用时: 1ms, 内存消耗: 336KB, 提交时间: 2020-07-16
#include<stdio.h> #include<malloc.h> #include<string.h> #define maxlenname 12 int main() { int i, j, k; int numpeople, numvotepeople; int totcount, Invalid; char *name[100], *vote[100]; char *point, *point1; char str[maxlenname], str1[maxlenname]; int *count; while(scanf("%d",&numpeople)!= EOF) { scanf("%d",&numpeople); for(i=0;i<numpeople;i++) { name[i] = (char *)malloc(maxlenname*sizeof(char)); } count = (int *)malloc((numpeople)*sizeof(int)); *count = 0; // for(i=0;i<numpeople+1;i++) // { // printf("d=%d",count[i]); // } for(i=0;i<numpeople;i++) { scanf("%s",&str); strcpy(name[i], str); } //printf("numpeople=%d \n",numpeople); //for(i=0;i<numpeople;i++) //{ // printf("%s \n",name[i]); //} scanf("%d", &numvotepeople); // printf("numvotepeople=%d \n",numvotepeople); for(i=0;i<numvotepeople;i++) { vote[i] = (char *)malloc(maxlenname*sizeof(char)); } for(i=0;i<numvotepeople;i++) { scanf("%s",&str1); strcpy(vote[i], str1); } // for(i=0;i<numvotepeople;i++) // { // printf("%s \n",vote[i]); // } // printf("olp %d \n", numvotepeople ); for(i=0;i<numvotepeople;i++) { //printf("olp11 \n"); for(j=0;j<numpeople;j++) { //printf("str=%s %s",name[j],vote[i]); if( strcmp(name[j],vote[i]) == 0 ) { count[j]++; //printf("str1=%s : %d \n",name[j],count[j]); break; } } //printf("olp66 \n"); } totcount = 0; for(i=0;i<numpeople;i++) { totcount = totcount + count[i]; } Invalid = numvotepeople - totcount; for(i=0;i<numpeople;i++) { printf("%s : %d \n",name[i],count[i]); } printf("Invalid : %d \n", Invalid); } return 0; }
C 解法, 执行用时: 1ms, 内存消耗: 344KB, 提交时间: 2021-09-08
#include<stdlib.h> #include<stdio.h> #include<string.h> typedef struct Candidate { char name[20]; int cnt; }Candidate; int main() { int candidates_num = 0, vate_num = 0; while (~scanf("%d", &candidates_num)) { Candidate *can = (Candidate *)malloc(sizeof(Candidate) * candidates_num); for (int i = 0; i < candidates_num; i++) { scanf("%s", can[i].name); can[i].cnt = 0; } scanf("%d", &vate_num); char temp[20] = {'\0'}; int invalid = 0; for (int i = 0; i < vate_num; i++) { scanf("%s", temp); int flag = 0; for (int j=0; j<candidates_num;j++){ if (strcmp(temp,can[j].name) == 0) { can[j].cnt++; flag = 1; } } if (!flag) invalid++; } for (int i=0; i<candidates_num; i++) { printf("%s : %d\n",can[i].name, can[i].cnt); } printf("Invalid : %d\n",invalid); free(can); } return 0; }