首页 > 试题广场 >

记票统计

[编程题]记票统计
  • 热度指数:136940 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}某场选举一共有 n 位候选人入选,候选人的名字均由大写字母构成,且互不相同,使用 c_1, c_2, \dots, c_n 表示。
\hspace{15pt}选举结束后,统计了 m 张选票,每张选票上均写有候选人的名字,使用 v_1, v_2, \dots, v_m 表示。
\hspace{15pt}求解每个候选人获得的票数。特别地,如果某张选票上的候选人名字不在候选名单中,则该票视为无效票。你需要同时统计无效票的数量。

输入描述:
\hspace{15pt}第一行输入一个整数 n \left(1 \leqq n \leqq 100\right) 代表候选人数。
\hspace{15pt}第二行输入 n 个长度为 1 \leqq {\rm len}(c_i) \leqq 10、仅由大写字母构成的字符串 c_1, c_2, \dots, c_n,代表候选人的名字。保证候选人的名字互不相同。
\hspace{15pt}第三行输入一个整数 m \left(1 \leqq m \leqq 100\right) 代表投票人数。
\hspace{15pt}第四行输入 m 个长度为 1 \leqq {\rm len}(v_i) \leqq 10、仅由大写字母构成的字符串 v_1, v_2, \dots, v_m,代表投票内容。


输出描述:
\hspace{15pt}对于每一位候选人,新起一行。先输出其名字,随后输出一个空格、一个冒号、一个空格作为间隔,最后输出其获得的票数。形如 c_i \texttt{ : } {\rm numbers}_i,其中 c_i 是候选人的名字,{\rm numbers}_i 是候选人的票数。
\hspace{15pt}最后一行以相同的格式输出无效票的数量。形如 \texttt{Invalid : } {\rm numbers},其中 {\rm numbers} 是无效票的数量。
示例1

输入

4
A B C D
8
A D E CF A GG A B

输出

A : 3
B : 1
C : 0
D : 1
Invalid : 3

说明

\hspace{15pt}在这个样例中,\texttt{E},\texttt{CF},\texttt{GG} 三张票是无效的。
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int n = in.nextInt();
            in.nextLine();
            String a = in.nextLine();
            String[] arr = a.split(" ");//将被投票人分割放入数组
            int m = in.nextInt();
            in.nextLine();
            String b = in.nextLine();
            String[] arr2 = b.split(" ");//将投票分割放入数组
            int[][] count = new int[n+1][1];//用来计数,按照角标与投票人数组arr对比来获取票数,多出一个为无效票
            // 优化:使用Map存储候选人及其票数,查找效率更高
            Map<String, Integer> voteCount = new HashMap<>();
            for (String s : arr){// 初始化候选人票数为0
                voteCount.put(s,0);
            }
            int invalidCount = 0;//无效票数
            //统计票数
            for (String s : arr2 ){
                if (voteCount.containsKey(s)){
                    voteCount.put(s,voteCount.get(s)+1);// 有效票,票数+1
                } else {
                    invalidCount++;// 无效票数+1
                }
            }    
            // 输出结果(按照原始候选人顺序)
            for (String s : arr){
                 System.out.println(s +" : " + voteCount.get(s));
            }      
            // 输出无效票  
            System.out.println("Invalid : " + invalidCount);
            // for (int i = 0 ; i <= n ;i ++){//初始化计数
            //     count[i][0] = 0; 
            // }
            // for (int i = 0 ; i < arr2.length;i++){
            //     boolean flag = true;//用来标记,没有匹配的被投票人时,将无效票数+1
            //     for (int j = 0;j< arr.length;j++){
            //         if (arr2[i].equals(arr[j])){
            //             count[j][0] += 1;
            //             flag = false;
            //             break;//已经匹配好被投票人,退出当前循环
            //         } 
            //     }
            //     if (flag){
            //         count[n][0] += 1;//无效票+1
            //     }
            // }
            // //输出结果
            // for (int i = 0 ; i <= n ; i++){
            //     if (i != n){//前n个结果直接输出相应的被投票人和结果
            //         System.out.print(arr[i] + " " + ":" + " " + count[i][0] + "\n");
            //     } else {//最后一个输出无效票
            //         System.out.print(  "Invalid " + ":" + " " + count[n][0] + "\n");
            //     }
            // }
        }
    }
}

发表于 2025-09-14 22:52:02 回复(0)
java版本:注意HashMap是不按照插入顺序来的,要用LinkedHashMap,保证插入key的顺序和存储key顺序相同。
import java.util.Scanner;
import java.util.LinkedHashMap;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int speakers = in.nextInt();
            in.nextLine();
            LinkedHashMap<String, Integer> speakersMap = new LinkedHashMap<>();
            for (int i = 0; i < speakers; i++){
                speakersMap.put(in.next(), 0);
            }
            int voters = in.nextInt();
            in.nextLine();
            String[] voterMap = in.nextLine().split(" ");
            int inValid = 0;
            for (int i = 0; i < voterMap.length; i++){
                if (speakersMap.containsKey(voterMap[i])){
                    speakersMap.merge(voterMap[i], 1, Integer :: sum);
                }else{
                    inValid++;
                }
            }
            for (String temp : speakersMap.keySet()){
                System.out.println(temp + " : " + speakersMap.get(temp));
            }
            System.out.println("Invalid : " + inValid);
        }
    }
} 

发表于 2025-07-18 03:06:42 回复(0)
题目不够严谨啊。也没有说明候选人返回的顺序问题。
发表于 2025-05-09 15:16:40 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = Integer.parseInt(in.nextLine());
            String[] arrN = in.nextLine().split(" ");
            int m = Integer.parseInt(in.nextLine());
            String[] arrM = in.nextLine().split(" ");
            Map<String, Integer> map = new LinkedHashMap<>();
            for (int i = 0; i < n; i++) {
                map.put(arrN[i], 0);
            }
            int count = 0;
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (arrN[i].equalsIgnoreCase(arrM[j])) {
                        count += 1;
                        map.put(arrN[i], map.getOrDefault(arrN[i], 0) + 1);
                    }
                }
            }
            map.put("Invalid", m - count);
            map.forEach((key, value)-> {
                System.out.println(key + " : " + value);
            });
        }
    }
}
发表于 2025-03-28 12:30:34 回复(0)

LinkedHashMap 维护插入顺序

发表于 2025-01-29 10:20:10 回复(0)
import java.util.Scanner; 
import java.util.LinkedHashMap;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        LinkedHashMap<String, Integer> h = new LinkedHashMap<>();
        for (int i = 0; i < n; i++) {
            h.put(in.next(), 0);
        }
        int p = in.nextInt();
        for (int i = 0; i < p; i++) {
            String name = in.next();
            if (h.containsKey(name)) {
                h.put(name, h.get(name)+1);
            }
        }
        int count = 0;
        for (String k : h.keySet()) {
            System.out.println(k + " : " + h.get(k));
            count += h.get(k);
        }
        System.out.println("Invalid : " + (p - count));
    }
}
发表于 2024-10-03 09:57:15 回复(0)
import java.util.Scanner;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        LinkedHashMap<String, Integer> hm = new LinkedHashMap();
        for (int i = 0; i < num; i++) {
            hm.put(sc.next(), 0);
        }
        int num2 = sc.nextInt();
        int InvalidNum=0;
        for (int i = 0; i < num2; i++) {
            String name = sc.next();
            if(hm.containsKey(name)){
                int count=hm.get(name);
                hm.put(name,++count);
            }else{
                InvalidNum++;
            }
        }
        for(Map.Entry<String,Integer> entry:hm.entrySet()){
            System.out.println(entry.getKey()+" : "+entry.getValue());
        }
        System.out.println("Invalid : "+InvalidNum);

    }
}

编辑于 2024-03-28 16:11:54 回复(0)
import java.util.*;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        in.nextLine();
        String s = in.nextLine();
        s=" "+s+" ";
        in.nextLine();
        String s1 = in.nextLine();
        Map<String,Integer> map = new HashMap();
        for(String temp:s1.split(" ")){
            if(s.contains(" "+temp+" ")){
                map.put(temp,map.getOrDefault(temp,0)+1);
            }else{
                map.put("Invalid",map.getOrDefault("Invalid",0)+1);
            }
        }
        for(String temp:s.trim().split(" ")){
            System.out.println(temp+" : "+map.getOrDefault(temp,0));
        }
        System.out.println("Invalid : "+map.getOrDefault("Invalid",0));
    }
}
编辑于 2024-01-21 10:58:40 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<String> list = new ArrayList();
        int n = in.nextInt();
        for(int i = 0; i < n; i++){
            list.add(in.next());
        }
        int m = in.nextInt();
        int err = 0;
        Map<String, Integer> map = new HashMap();
        for(int i = 0; i < m; i++){
            String s = in.next();
            if(list.contains(s)){
                map.put(s, map.getOrDefault(s, 0)+1);
            }else{
                err++;
            }
        }
        for(String name : list){
            System.out.println(name+" : "+ map.getOrDefault(name,0));
        }
        System.out.println("Invalid : "+err);
    }
}

发表于 2023-11-28 18:05:59 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int a = in.nextInt();
        List<String> listA = new ArrayList<>();
        List<String> listB = new ArrayList<>();
        while (a -- > 0) {
            listA.add(in.next());
        }
        int b = in.nextInt();
        while (b-- > 0) {
            listB.add(in.next());
        }
        Map<String, Integer> map = new HashMap<>();
        int invalid = 0;
        for (String list : listA) {
            map.put(list, 0);
        }
        for (String list : listB) {
            if (map.containsKey(list)) {
                map.put(list, map.getOrDefault(list, 0) + 1);
            } else {
                invalid++;
            }
        }
        listA.forEach(li -> {
            System.out.println(li + " : " + map.get(li));
        });
        System.out.println("Invalid : " + invalid);
    }
}

发表于 2023-06-08 15:12:34 回复(0)
。。。
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        int n1 = in.nextInt();
        // 初始化计数器
        for (int i = 0; i < n1; i++) {
            map.putIfAbsent(in.next(), 0);
        }
        map.put("Invalid", 0);
        // 计数
        int n2 = in.nextInt();
        for (int i = 0; i < n2; i++) {
            String d = in.next();
            if (map.containsKey(d)) {
                map.compute(d, (k, v) -> v + 1);
            } else {
                map.compute("Invalid", (k, v) -> v + 1);
            }
        }
        // 输出
        Set<Map.Entry<String, Integer>> set = map.entrySet();
        for (Map.Entry entry : set ) {
            System.out.println(String.format("%s : %d", entry.getKey(), entry.getValue()));
        }
    }
}

发表于 2023-05-15 23:51:42 回复(0)
实在没明白哪儿错了,本地运行正常
import java.util.HashMap;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int candidateNum = in.nextInt();
            HashMap<String,Integer> voteCount = new HashMap<>();
            for(int i=0;i<candidateNum;i++){
                voteCount.put(in.next(),0);
            }
            int voteNum = in.nextInt();
            for(int i=0;i<voteNum;i++){
                String key =in.next();
                Integer num = voteCount.get(key);
                if(num==null){
                    voteCount.put("Invalid",
                    voteCount.getOrDefault("Invalid",0)+1);
                }else{
                    voteCount.put(key,num+1);
                }
            }
            voteCount.keySet().forEach(key->{
                System.out.println(key+" : "+voteCount.get(key));
            });
        }
    }
}

发表于 2023-03-20 14:15:52 回复(1)
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            in.nextInt();
            in.nextLine();
            Map<String, Integer> map = Arrays.stream(in.nextLine().split(" ")).collect(Collectors.toMap(s -> s, s -> 0, (oldValue, newValue) -> 0, LinkedHashMap::new));
            map.put("Invalid", 0);
            int m = in.nextInt();
            while (m-- > 0) {
                Integer value = map.computeIfPresent(in.next(), (s, integer) -> integer + 1);
                map.compute("Invalid", (s, integer) -> integer + (value == null ? 1 : 0));
            }
            map.forEach((key, value) -> System.out.println(key + " : " + value));
        }
    }
}

发表于 2023-03-08 21:13:32 回复(0)
import java.util.Scanner;
import java.util.Objects;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
            int a = Integer.parseInt(in.nextLine());
            String[][] arr1 = new String[a][2];
            String str1 = in.nextLine();
            String[] arr2 = str1.split(" ");
            for (int i = 0; i < a; i++) {
                arr1[i][0] = arr2[i];
            }
            int b = Integer.parseInt(in.nextLine());
            String str2 = in.nextLine();
            String[] arr3 = str2.split(" ");
            int invalid = b;
            for (int i = 0; i < a; i++) {
                int num = 0;
                for (int j = 0; j < b; j++) {
                    if (Objects.equals(arr1[i][0], arr3[j])) {
                        num++;
                        invalid--;
                    }
                }
                arr1[i][1] = String.valueOf(num);
            }
            for (int i = 0; i < a; i++) {
                System.out.println(arr1[i][0] + " : " + arr1[i][1]);
            }
            System.out.println("Invalid : " + invalid);
        }
    }
}

发表于 2023-03-04 19:58:21 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int houXuanRenNumber = Integer.parseInt(br.readLine());
        String[] houXuanRens = br.readLine().split(" ");
        int touPiaoRenNumber = Integer.parseInt(br.readLine());
        String[] resultTouPiao = br.readLine().split(" ");
        // 保证插入顺序和取出顺序一致,使用LinkedHashMap集合
        LinkedHashMap<String, Integer> hashMap = new LinkedHashMap<>();
        int invalidNum = 0;
        for(int i = 0; i < houXuanRens.length; i++){
            hashMap.put(houXuanRens[i], 0);
        }
        hashMap.put("Invalid", 0);
        for(int i = 0; i < resultTouPiao.length; i++){
            String temp = resultTouPiao[i];
            if(hashMap.containsKey(temp)){
                hashMap.put(temp, hashMap.get(temp) + 1);
            }else{
                hashMap.put("Invalid", hashMap.get("Invalid") + 1);
            }
        }
        for(String key : hashMap.keySet()){
               System.out.println(key + " : " + hashMap.get(key));
           } 
    }
}

发表于 2022-08-14 13:54:16 回复(1)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        
        while((str=br.readLine())!=null){
            int cou=Integer.parseInt(str);
            int[] dd=new int[cou];
            String[] strArr=br.readLine().split(" ");
            int num=Integer.parseInt(br.readLine());
            String[] strArr1=br.readLine().split(" ");
            int inv=0;
            
            for(int i=0;i<strArr1.length;i++){
                boolean b=false;
                for(int j=0;j<strArr.length;j++){
                    if(strArr1[i].equals(strArr[j])){
                        dd[j]+=1;
                        b=true;
                        break;
                    }
                }
                if(!b){
                    inv++;
                }
            }
            for(int i=0;i<cou;i++){
                System.out.println(strArr[i]+" "+":"+" "+dd[i]);
            }
            System.out.println("Invalid : "+inv);
        }
    }
}

发表于 2022-08-02 13:13:35 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        sc.nextLine();
        Map<String, Integer> map = new HashMap();
        String[] nameArray = sc.nextLine().split(" ");
        List<String> nameList = new ArrayList<>();
        for (String str : nameArray) {
            map.put(str, 0);
            nameList.add(str);
        }
        sc.nextLine();
        String[] ticketArray = sc.nextLine().split(" ");
        for (String str : ticketArray) {
            if (map.containsKey(str)) {
                map.put(str, map.get(str) + 1);
            } else {
                map.put("Invalid", map.getOrDefault("Invalid", 0) + 1);
            }
        }
        for (String key : nameList) {
            Integer value = map.get(key);
            System.out.println(key + " : " + value);
        }
        System.out.println("Invalid : " + (map.get("Invalid") == null ? 0 : map.get("Invalid")));
    }
}
发表于 2022-07-10 15:42:30 回复(0)
import java.util.*;
import javax.script.*;
public class Main {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
       
        
        while(scan.hasNext())
        {
            Map<String,Integer> map=new LinkedHashMap();
            //非法参数
            int invalid=0;
            int n=Integer.parseInt(scan.nextLine());
            String s=scan.nextLine();
            //用空格分割开
            String str[]=s.split("\\s+");
            for(int i=0;i<str.length;i++)
            {
                map.put(str[i],0);
            }
            int m=Integer.parseInt(scan.nextLine());
            String str2[]=scan.nextLine().split("\\s+");
            for(int i=0;i<str2.length;i++)
            {
                if(map.containsKey(str2[i]))
                {
                    map.put(str2[i],map.get(str2[i])+1);
                }else 
                {
                    invalid++;
                }
            }
            for(Map.Entry<String,Integer > entry:map.entrySet()){
                System.out.print(entry.getKey()+" : "+entry.getValue()+"\n");
            }
            
            System.out.println("Invalid : "+invalid);
        }
       
    }

    
}

发表于 2022-07-04 18:37:16 回复(0)