编辑代码

#include <stdio.h>
#include <string.h>

// 结构体表示候选人
struct Candidate {
    char name[50];
    int votes;
};
// 哈希表
struct HashTable {
    struct Candidate candidates[1000];
};
// 哈希函数
int hashFunction(const char* name) {
    return strlen(name) % 1000;
}
// 添加投票
void vote(struct HashTable* hashTable, const char* candidateName) {
    int index = hashFunction(candidateName);
    // 检查是否已投过票
    if (hashTable->candidates[index].votes > 0 && strcmp(hashTable->candidates[index].name, candidateName) == 0) {
        printf("重复投票:%s\n", candidateName);
    } else {
        // 新增投票
        strcpy(hashTable->candidates[index].name, candidateName);
        hashTable->candidates[index].votes++;
        printf("投票成功:%s\n", candidateName);
    }
}

// 输出投票结果
void printResults(const struct HashTable* hashTable) {
    printf("投票结果:\n");
    for (int i = 0; i < 1000; i++) {
        if (hashTable->candidates[i].votes > 0) {
            printf("%s: %d票\n", hashTable->candidates[i].name, hashTable->candidates[i].votes);
        }
    }
}

int main() {
    struct HashTable election;
    memset(&election, 0, sizeof(election));

    // 模拟投票
    vote(&election, "C1");
    vote(&election, "C2");
    vote(&election, "C2"); // 重复投票
    vote(&election, "C3");

    // 输出结果
    printResults(&election);

    return 0;
}