解题思路

这是一个投票统计问题,需要统计每个候选人获得的有效票数以及无效票数。

关键点

  1. 输入格式:

    • 第一行:候选人数量
    • 第二行: 个候选人名字
    • 第三行:投票人数
    • 第四行:投票内容
  2. 处理要求:

    • 统计每个候选人的得票数
    • 统计无效票数(投给不存在候选人的票)
    • 按照输入顺序输出结果

代码

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
        // 读取候选人
        vector<string> candidates(n);
        map<string, int> votes;
        for (int i = 0; i < n; i++) {
            cin >> candidates[i];
            votes[candidates[i]] = 0;  // 初始化票数
        }
        
        // 读取投票
        int m;
        cin >> m;
        int invalid = 0;
        for (int i = 0; i < m; i++) {
            string vote;
            cin >> vote;
            if (votes.find(vote) != votes.end()) {
                votes[vote]++;
            } else {
                invalid++;
            }
        }
        
        // 输出结果
        for (const string& candidate : candidates) {
            cout << candidate << " : " << votes[candidate] << endl;
        }
        cout << "Invalid : " << invalid << endl;
    }
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int n = sc.nextInt();
            
            // 读取候选人
            String[] candidates = new String[n];
            Map<String, Integer> votes = new HashMap<>();
            for (int i = 0; i < n; i++) {
                candidates[i] = sc.next();
                votes.put(candidates[i], 0);  // 初始化票数
            }
            
            // 读取投票
            int m = sc.nextInt();
            int invalid = 0;
            for (int i = 0; i < m; i++) {
                String vote = sc.next();
                if (votes.containsKey(vote)) {
                    votes.put(vote, votes.get(vote) + 1);
                } else {
                    invalid++;
                }
            }
            
            // 输出结果
            for (String candidate : candidates) {
                System.out.println(candidate + " : " + votes.get(candidate));
            }
            System.out.println("Invalid : " + invalid);
        }
    }
}
while True:
    try:
        # 读取候选人
        n = int(input())
        candidates = input().split()
        votes = {name: 0 for name in candidates}
        
        # 读取投票
        m = int(input())
        vote_list = input().split()
        
        # 统计票数
        invalid = 0
        for vote in vote_list:
            if vote in votes:
                votes[vote] += 1
            else:
                invalid += 1
        
        # 输出结果
        for candidate in candidates:
            print(f"{candidate} : {votes[candidate]}")
        print(f"Invalid : {invalid}")
        
    except:
        break

算法及复杂度

算法分析

  1. 使用哈希表存储每个候选人的票数
  2. 遍历投票列表,统计有效票和无效票
  3. 按原始顺序输出结果

复杂度分析

  • 时间复杂度: - 是候选人数量, 是投票数量
  • 空间复杂度: - 需要存储候选人及其票数