pvjc26/du2/program.c
2026-03-05 13:46:16 +01:00

70 lines
1.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 1024
#define MAX_NAME 256
typedef struct {
char name[MAX_NAME];
int votes;
} Student;
Student students[MAX_STUDENTS];
int count = 0;
int find(const char *name) {
for (int i = 0; i < count; i++) {
if (strcmp(students[i].name, name) == 0) return i;
}
return -1;
}
int cmp(const void *a, const void *b) {
const Student *sa = (const Student *)a;
const Student *sb = (const Student *)b;
if (sb->votes != sa->votes) return sb->votes - sa->votes;
return strcmp(sa->name, sb->name);
}
int main() {
char line[MAX_NAME + 32];
int loaded = 0;
while (fgets(line, sizeof(line), stdin) != NULL) {
int votes;
char name[MAX_NAME];
line[strcspn(line, "\n")] = '\0';
if (sscanf(line, "%d %255[^\n]", &votes, name) != 2 || votes <= 0) {
break;
}
loaded++;
int idx = find(name);
if (idx >= 0) {
students[idx].votes += votes;
} else {
if (count >= MAX_STUDENTS) break;
strncpy(students[count].name, name, MAX_NAME - 1);
students[count].votes = votes;
count++;
}
}
if (loaded == 0) {
printf("Nepodarilo nacitat nic\n");
return 0;
}
qsort(students, count, sizeof(Student), cmp);
printf("Vysledky:\n");
for (int i = 0; i < count; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
}
return 0;
}