This commit is contained in:
Oleksandr Vyshniakov 2025-03-20 17:34:37 +01:00
parent 1b0f27ad83
commit acf707a594
2 changed files with 51 additions and 39 deletions

View File

@ -1,63 +1,75 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <ctype.h>
#define MAX_NAME_LENGTH 100 #define namemax 100
#define maxstudents 1000
typedef struct { typedef struct {
char name[MAX_NAME_LENGTH]; char name[namemax];
int votes; int golosa;
} Student; } Student;
int compare_students(const void *a, const void *b) { int find_student(Student students[], int count, char *name) {
const Student *studentA = (const Student *)a; for (int i = 0; i < count; i++) {
const Student *studentB = (const Student *)b; if (strcmp(students[i].name, name) == 0) {
return i;
if (studentA->votes != studentB->votes) { }
return studentB->votes - studentA->votes;
} else {
return strcmp(studentA->name, studentB->name);
} }
return -1;
}
int compare(const void *a, const void *b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
if (studentA->golosa != studentB->golosa) {
return studentB->golosa - studentA->golosa;
}
return strcmp(studentA->name, studentB->name);
} }
int main() { int main() {
Student students[100]; Student students[maxstudents];
int student_count = 0; int count = 0;
char line[256]; char buffer[200];
while (fgets(line, sizeof(line), stdin)) { while (fgets(buffer, sizeof(buffer), stdin)) {
int votes; buffer[strcspn(buffer, "\n")] = '\0';
char name[MAX_NAME_LENGTH];
if (sscanf(line, "%d %[^\n]", &votes, name) != 2) { if (strlen(buffer) == 0) {
break; break;
int found = 0;
for (int i = 0; i < student_count; i++) {
if (strcmp(students[i].name, name) == 0) {
students[i].votes += votes;
found = 1;
break;
}
} }
int golosa;
char name[namemax];
if (sscanf(buffer, "%d %99[^\n]", &golosa, name) != 2 || golosa <= 0) {
printf("Chyba: Nepodarilo sa nacitat ziadny zaznam.\n");
return 0;
}
int index = find_student(students, count, name);
if (index != -1) {
students[index].golosa += golosa;
} else {
strcpy(students[count].name, name);
students[count].golosa = golosa;
count++;
}
} }
if (student_count == 0) { if (count == 0) {
printf("Chyba: nepodarilo sa nacitat ziadny zaznam.\n"); printf("Chyba: Nepodarilo sa nacitat ziadny zaznam.\n");
return 1; return 0;
} }
qsort(students, count, sizeof(Student), compare);
qsort(students, student_count, sizeof(Student), compare_students);
for (int i = 0; i < count; i++) {
printf("Vysledky:\n"); printf("%s %d\n", students[i].name, students[i].golosa);
for (int i = 0; i < student_count; i++) {
printf("%d %s\n", students[i].votes, students[i].name);
} }
return 0; return 0;

Binary file not shown.