funguje
This commit is contained in:
parent
aa54a6d151
commit
d8cc432763
77
cv5/program.c
Normal file
77
cv5/program.c
Normal file
@ -0,0 +1,77 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_NAME_LENGTH 100
|
||||
|
||||
typedef struct {
|
||||
char name[MAX_NAME_LENGTH];
|
||||
int votes;
|
||||
} Candidate;
|
||||
|
||||
int compare_candidates(const void *a, const void *b) {
|
||||
const Candidate *candidate_a = (const Candidate *)a;
|
||||
const Candidate *candidate_b = (const Candidate *)b;
|
||||
|
||||
// Sort by number of votes in descending order
|
||||
if (candidate_a->votes != candidate_b->votes) {
|
||||
return candidate_b->votes - candidate_a->votes;
|
||||
} else {
|
||||
// If votes are tied, sort lexicographically by name
|
||||
return strcmp(candidate_a->name, candidate_b->name);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
Candidate candidates[100]; // Assuming no more than 100 candidates
|
||||
int num_candidates = 0;
|
||||
|
||||
// Read votes from standard input
|
||||
while (1) {
|
||||
int votes;
|
||||
char name[MAX_NAME_LENGTH];
|
||||
|
||||
// Try to read votes and name
|
||||
if (scanf("%d %99s", &votes, name) != 2) {
|
||||
if (feof(stdin)) {
|
||||
break; // End of input
|
||||
} else {
|
||||
printf("Error: Failed to read vote.\n");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the candidate already exists
|
||||
int found = 0;
|
||||
for (int i = 0; i < num_candidates; i++) {
|
||||
if (strcmp(candidates[i].name, name) == 0) {
|
||||
candidates[i].votes += votes;
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If the candidate is not found, add a new candidate
|
||||
if (!found) {
|
||||
if (num_candidates >= 100) {
|
||||
printf("Error: Too many candidates.\n");
|
||||
return 1;
|
||||
}
|
||||
strcpy(candidates[num_candidates].name, name);
|
||||
candidates[num_candidates].votes = votes;
|
||||
num_candidates++;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the candidates
|
||||
qsort(candidates, num_candidates, sizeof(Candidate), compare_candidates);
|
||||
|
||||
// Print the outcome
|
||||
printf("Outcome:\n");
|
||||
for (int i = 0; i < num_candidates; i++) {
|
||||
printf("%d %s\n", candidates[i].votes, candidates[i].name);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user