#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CANDIDATES 100
typedef struct {
char name[50];
int votes;
} Candidate;
typedef struct {
Candidate candidates[MAX_CANDIDATES];
int count;
} HashTable;
unsigned int hash(const char* str) {
unsigned int hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c;
}
return hash % MAX_CANDIDATES;
}
void initialize_hash_table(HashTable* table) {
table->count = 0;
for (int i = 0; i < MAX_CANDIDATES; i++) {
table->candidates[i].votes = 0;
strcpy(table->candidates[i].name, "");
}
}
void add_vote(HashTable* table, const char* candidate_name) {
unsigned int index = hash(candidate_name);
while (strcmp(table->candidates[index].name, "") != 0) {
if (strcmp(table->candidates[index].name, candidate_name) == 0) {
table->candidates[index].votes++;
return;
}
index = (index + 1) % MAX_CANDIDATES;
}
strcpy(table->candidates[index].name, candidate_name);
table->candidates[index].votes++;
table->count++;
}
void print_results(const HashTable* table) {
for (int i = 0; i < MAX_CANDIDATES; i++) {
if (strcmp(table->candidates[i].name, "") != 0) {
printf("%s获得 %d 票\n", table->candidates[i].name, table->candidates[i].votes);
}
}
}
int main() {
HashTable vote_table;
initialize_hash_table(&vote_table);
add_vote(&vote_table, "许许");
add_vote(&vote_table, "许许");
add_vote(&vote_table, "希希");
add_vote(&vote_table, "许许");
add_vote(&vote_table, "嘻嘻");
add_vote(&vote_table, "嘻嘻");
print_results(&vote_table);
return 0;
}