华为OD机试双机位C卷 - 明日之星选举 (JAVA & Python & C/ C++ & JS & GO)

明日之星选举

2026华为OD机试双机位C卷 - 华为OD上机考试双机位C卷 100分题型

华为OD机试双机位C卷真题目录点击查看: 华为OD机试双机位C卷真题题库目录|机考题库 + 算法考点详解

题目描述

给定一组选票votes[],vote[i]代表第i张选票的内容,包含一个字符串"zhangsan,hanmei",表示推荐zhangsan称为明日之星,返回hanmei称为明日之星。赞成或返回使用逗号(,)分割。

给定一个数组n,表示最后将筛选成票最多的n个人,如果赞成票相同,则反对票越少,排序越靠前;如果赞成票和反对票都相同,则按照姓名字典序升序排序。

注意:

  • 1 <= votes.length <= 500

  • 1 <= votes[i].length <= 20

  • vote[i]由小写字母和逗号组成,且最多只有一个逗号。

  • vote[i]中赞成票必选,反对票可选。

  • n的取值范围为[1, 不同姓名的数量]

输入描述

第一行输入为M,表示选票的数量,其中1 <= M <= 500

接下来M行为选票具体内容

最后一行输入为N,表示最终当选明日之星的人员个数1 <= N <= 不同姓名的数量

输出描述

输出一个字符串,返回当选的N个人的姓名,顺序排列,逗号分割。

用例1

输入

none 复制代码
6
zhangsan,hanmei
zhangsan,lisi
lisi
lisi
wangwu
hanmei
2

输出

none 复制代码
zhangsan,lisi

示例二

输入

复制代码
4
zhangsan,lisi
lisi,wangwu
wangwu,qianliu
qianliu,zhangsan
2

输出

复制代码
lisi,qianliu

说明

复制代码
zhangsan:1赞成,1反对
lisi:1赞成,1反对
wangwu:1赞成,1反对
qianliu:1赞成,1反对
票数情况相同,按照字典序升序,返回lisi,qianliu

题解

思路:逻辑分析 + 在自定义排序

  1. 自定义结构体或者类存储所有出现人的选票情况,对于python和C++等语言统计选票可以使用哈希表进行处理,C语言通过线性扫描也是可以的。
  2. 将所有人的选票情况使用一个类/结构体数组存储,然后按照题目要求进行排序即可。
  3. 按照题目要求规则输出前n个人的名字。

c++

c++ 复制代码
#include<iostream>
#include<vector>
#include<string>
#include <utility> 
#include <sstream>
#include<algorithm> 
#include<cmath>
#include<map>
#include<set>
using namespace std;


struct Person{
    string name;
    int agreeCount;
    int disagreeCount;
    Person(){}
    Person(string name, int agreeCount, int disagreeCount): name(name), agreeCount(agreeCount), disagreeCount(disagreeCount){}
};

// 通用 切割函数 函数 将字符串str根据delimiter进行切割
vector<string> split(const string& str, const string& delimiter) {
    vector<string> result;
    size_t start = 0;
    size_t end = str.find(delimiter);
    while (end != string::npos) {
        result.push_back(str.substr(start, end - start));
        start = end + delimiter.length();
        end = str.find(delimiter, start);
    }
    // 添加最后一个部分
    result.push_back(str.substr(start));
    return result;
}





int main() {
    int m;
    cin >> m;
    // 存储每个人同意票数/不同票数
    map<string,int> personAgreeNum;
    map<string,int> personDisagreeNum;  
    // 所有出现的名字
    set<string> allName;

    for (int i = 0; i < m; i++) {
        string vote;
        cin >> vote;
        vector<string> voteName = split(vote, ",");
        personAgreeNum[voteName[0]]++;
        allName.insert(voteName[0]);
        // 可选
        if (voteName.size() == 2) {
           personDisagreeNum[voteName[1]]++; 
           allName.insert(voteName[1]);
        }
    }

    int n;
    cin >> n;

    vector<Person> allPeopleScore;
    for (auto& name : allName) {
        allPeopleScore.push_back({name, personAgreeNum[name], personDisagreeNum[name]});
    }

    // 自定义排序
    sort(allPeopleScore.begin(), allPeopleScore.end(), [](Person &a, Person &b) {
        if (a.agreeCount == b.agreeCount) {
            if (a.disagreeCount == b.disagreeCount) {
                return a.name < b.name;
            }
            return a.disagreeCount < b.disagreeCount;
        }
        return a.agreeCount > b.agreeCount;
    });

    // 输出结果
    for (int i = 0; i < n; i++) {
        if (i != 0) {
            cout << ",";
        }
        cout << allPeopleScore[i].name;
    }

    return 0;
}

C语言

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXN 1000
#define NAMELEN 25

typedef struct {
    char name[NAMELEN];
    int agree;
    int disagree;
} Person;

Person people[MAXN];
int cnt = 0;

// 查找人名,存在返回下标,不存在返回 -1
int find(char *name) {
    for (int i = 0; i < cnt; i++) {
        if (strcmp(people[i].name, name) == 0) {
            return i;
        }
    }
    return -1;
}

// 排序规则
int cmp(const void *a, const void *b) {
    Person *x = (Person *)a;
    Person *y = (Person *)b;

    if (x->agree != y->agree)
        return y->agree - x->agree;      // 同意票多的优先
    if (x->disagree != y->disagree)
        return x->disagree - y->disagree;// 反对票少的优先
    return strcmp(x->name, y->name);     // 名字字典序
}

int main() {
    int m;
    scanf("%d", &m);

    for (int i = 0; i < m; i++) {
        char s[2 * NAMELEN];
        scanf("%s", s);

        char *p = strchr(s, ',');

        if (p) {
            *p = '\0';
            char *a = s;
            char *b = p + 1;

            int ia = find(a);
            if (ia == -1) {
                strcpy(people[cnt].name, a);
                people[cnt].agree = 1;
                people[cnt].disagree = 0;
                cnt++;
            } else {
                people[ia].agree++;
            }

            int ib = find(b);
            if (ib == -1) {
                strcpy(people[cnt].name, b);
                people[cnt].agree = 0;
                people[cnt].disagree = 1;
                cnt++;
            } else {
                people[ib].disagree++;
            }

        } else {
            int idx = find(s);
            if (idx == -1) {
                strcpy(people[cnt].name, s);
                people[cnt].agree = 1;
                people[cnt].disagree = 0;
                cnt++;
            } else {
                people[idx].agree++;
            }
        }
    }

    int n;
    scanf("%d", &n);
    // 自定义排序
    qsort(people, cnt, sizeof(Person), cmp);

    for (int i = 0; i < n; i++) {
        if (i) printf(",");
        printf("%s", people[i].name);
    }

    return 0;
}

JAVA

JAVA 复制代码
import java.io.*;
import java.util.*;

public class Main {

    static class Person {
        String name;
        int agreeCount;
        int disagreeCount;

        Person(String name, int agreeCount, int disagreeCount) {
            this.name = name;
            this.agreeCount = agreeCount;
            this.disagreeCount = disagreeCount;
        }
    }

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        int m = Integer.parseInt(br.readLine());

        // 存储每个人同意票数 / 不同意票数
        Map<String, Integer> agreeMap = new HashMap<>();
        Map<String, Integer> disagreeMap = new HashMap<>();
        // 所有出现的名字
        Set<String> allName = new HashSet<>();

        for (int i = 0; i < m; i++) {
            String vote = br.readLine();
            String[] arr = vote.split(",");

            agreeMap.put(arr[0], agreeMap.getOrDefault(arr[0], 0) + 1);
            allName.add(arr[0]);
            // 返回票可选
            if (arr.length == 2) {
                disagreeMap.put(arr[1], disagreeMap.getOrDefault(arr[1], 0) + 1);
                allName.add(arr[1]);
            }
        }

        int n = Integer.parseInt(br.readLine());
      
        List<Person> list = new ArrayList<>();
        // 统一用数组存储
        for (String name : allName) {
            list.add(new Person(
                    name,
                    agreeMap.getOrDefault(name, 0),
                    disagreeMap.getOrDefault(name, 0)
            ));
        }

        // 自定义排序
        list.sort((a, b) -> {
            if (a.agreeCount != b.agreeCount)
                return b.agreeCount - a.agreeCount;
            if (a.disagreeCount != b.disagreeCount)
                return a.disagreeCount - b.disagreeCount;
            return a.name.compareTo(b.name);
        });
        
        // 构建结果
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (i > 0) sb.append(",");
            sb.append(list.get(i).name);
        }
        System.out.println(sb.toString());
    }
}

Python

python 复制代码
import sys

def main():
    input = sys.stdin.readline

    m = int(input())

    # 存储每个人同意票数 / 不同意票数
    agree = {}
    disagree = {}
    # 所有出现的名字
    all_name = set()

    for _ in range(m):
        vote = input().strip()
        arr = vote.split(",")

        agree[arr[0]] = agree.get(arr[0], 0) + 1
        all_name.add(arr[0])

        if len(arr) == 2:
            disagree[arr[1]] = disagree.get(arr[1], 0) + 1
            all_name.add(arr[1])

    n = int(input())

    people = []
    for name in all_name:
        people.append((
            -agree.get(name, 0),   # 取负数用于降序
            disagree.get(name, 0),
            name
        ))

    # 排序规则:同意票降序,不同意票升序,名字字典序
    people.sort()

    result = [people[i][2] for i in range(n)]
    print(",".join(result))


if __name__ == "__main__":
    main()

JavaScript

js 复制代码
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

let lines = [];
rl.on('line', (line) => {
    lines.push(line.trim());
});

rl.on('close', () => {
    let idx = 0;

    const m = parseInt(lines[idx++], 10);

    // 存储每个人同意票数 / 不同意票数
    const agree = new Map();
    const disagree = new Map();
    const allName = new Set();

    for (let i = 0; i < m; i++) {
        const vote = lines[idx++];
        const arr = vote.split(',');

        agree.set(arr[0], (agree.get(arr[0]) || 0) + 1);
        allName.add(arr[0]);

        // 可选的反对票
        if (arr.length === 2) {
            disagree.set(arr[1], (disagree.get(arr[1]) || 0) + 1);
            allName.add(arr[1]);
        }
    }

    const n = parseInt(lines[idx++], 10);

    // 构造人员信息列表
    let people = [];
    for (let name of allName) {
        people.push({
            name: name,
            agreeCount: agree.get(name) || 0,
            disagreeCount: disagree.get(name) || 0
        });
    }

    // 自定义排序:
    // 1. 同意票多的在前
    // 2. 不同意票少的在前
    // 3. 名字字典序
    people.sort((a, b) => {
        if (a.agreeCount !== b.agreeCount) {
            return b.agreeCount - a.agreeCount;
        }
        if (a.disagreeCount !== b.disagreeCount) {
            return a.disagreeCount - b.disagreeCount;
        }
        return a.name.localeCompare(b.name);
    });

    // 输出前 n 个名字
    let result = [];
    for (let i = 0; i < n; i++) {
        result.push(people[i].name);
    }

    console.log(result.join(','));
});

Go

go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strings"
)

type Person struct {
	name          string
	agreeCount    int
	disagreeCount int
}

func main() {
	in := bufio.NewReader(os.Stdin)

	var m int
	fmt.Fscan(in, &m)

	// 存储每个人同意票数 / 不同意票数
	agree := make(map[string]int)
	disagree := make(map[string]int)
	// 所有出现的名字
	allName := make(map[string]bool)

	for i := 0; i < m; i++ {
		var vote string
		fmt.Fscan(in, &vote)

		arr := strings.Split(vote, ",")

		agree[arr[0]]++
		allName[arr[0]] = true
		// 返回掉可选
		if len(arr) == 2 {
			disagree[arr[1]]++
			allName[arr[1]] = true
		}
	}

	var n int
	fmt.Fscan(in, &n)

	people := make([]Person, 0)
	for name := range allName {
		people = append(people, Person{
			name:          name,
			agreeCount:    agree[name],
			disagreeCount: disagree[name],
		})
	}

	// 自定义排序
	sort.Slice(people, func(i, j int) bool {
		if people[i].agreeCount != people[j].agreeCount {
			return people[i].agreeCount > people[j].agreeCount
		}
		if people[i].disagreeCount != people[j].disagreeCount {
			return people[i].disagreeCount < people[j].disagreeCount
		}
		return people[i].name < people[j].name
	})
    // 输出结果
	for i := 0; i < n; i++ {
		if i > 0 {
			fmt.Print(",")
		}
		fmt.Print(people[i].name)
	}
}
相关推荐
西电研梦1 天前
26西电考研 | 寒假开始,机试 or C语言程序设计怎么准备?
c语言·考研·华为od·研究生·西安电子科技大学·计算机408
无限码力2 天前
华为OD技术面真题 - Mysql相关 - 4
mysql·华为od·华为od技术面真题·华为od技术面八股·华为od技术面八股文·华为od技术面mysql相关
无限码力2 天前
华为OD机试双机位C卷 - FLASH坏块监测系统 (C语言 & C++ & Python & JAVA & JS & GO)
华为od·华为od机试真题·华为od机试双机位c卷·华为od上机考试双机位c卷·华为od上机考试真题·华为od机考真题·华为odflash坏块监测系统
无限码力2 天前
华为OD技术面真题 - 计算机网络相关 - 4
计算机网络·华为od·华为od技术面真题·华为od技术面计算机八股·华为od技术面计算机网络真题
想七想八不如114083 天前
2019机试真题
java·华为od·华为
开开心心_Every6 天前
家常菜谱软件推荐:分类齐全无广告步骤详细
linux·运维·服务器·华为od·edge·pdf·华为云
无限码力7 天前
华为OD2026最新机试双机位C卷机考真题目录含考点说明 (持续更新)
华为od·华为od机考·华为od题库·华为od机试·华为od机试双机位c卷·华为od最新上机考试题库·od机考题库
无限码力7 天前
华为OD技术面真题 - 数据库MySQL - 3
数据库·mysql·华为od·八股文·华为od技术面八股文
无限码力7 天前
华为OD技术面真题 - JAVA开发 - 5
java·华为od·面试·华为od技术面真题·华为od技术面八股·华为od技术面java八股文