TB椰程 TypeBuddy 打字搭子

2024-03 · 7级 · 交流问题

GESP 标程 · 考级真题 · 代码 · cpp · 难度 5/5 · 共 1678 字

CCF 原卷官方标程 · 数组与向量、STL、位运算、搜索 · 本地编译通过

  • 2024-03
  • 数组与向量

正文

// GESP 2024-03 C++ 7级 编程题 1 · 交流问题
// 原题:https://oj.yecheng.tv/p/gs2403l7p1
// 官方原卷:https://gesp.ccf.org.cn/101/attach/1602047231131680.pdf
// 题意:来自 2 所学校 A 校、B 校的名同学相聚在一起相互交流,方便起见,我们把这些同学从至编号。
// 知识点:数组与向量、STL、位运算、搜索
// 参考程序:CCF 原卷官方标程,PDF 抽取后已去行号;本地编译核验通过,供打字练习
// 原卷样例验证:样例验证 2/2 通过
//
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
void dfs(vector<vector<int>>& graph, int node, vector<int>& colors, int* color_cnt,
    int curr_color) {
    colors[node] = curr_color;
    color_cnt[curr_color]++;
    for (int neighbor : graph[node]) {
        if (colors[neighbor] == -1) {
            dfs(graph, neighbor, colors, color_cnt, curr_color ^ 1);
        }
    }
}
pair<int, int> find_b_school_students(int N, vector<pair<int, int>>& connections) {
    vector<vector<int>> graph(N + 1);
    for (const auto& connection : connections) {
        graph[connection.first].push_back(connection.second);
        graph[connection.second].push_back(connection.first);
    }
    vector<int> colors(N + 1, -1);
    int min_ans = 0;
    for (int i = 1; i <= N; ++i) {
        if (colors[i] == -1) {
            int color_cnt[2] = {0, 0};
            dfs(graph, i, colors, color_cnt, 0);
            min_ans += min(color_cnt[0], color_cnt[1]);
        }
    }
    return make_pair(min_ans, N - min_ans);
}
int main() {
    int N, M;
    cin >> N >> M;
    vector<pair<int, int>> connections(M);
    for (int i = 0; i < M; ++i) {
        cin >> connections[i].first >> connections[i].second;
    }
    pair<int, int> b_students = find_b_school_students(N, connections);
    cout << b_students.first << " " << b_students.second << endl;
    return 0;
}

GESP 标程 · 考级真题的其它内容

打字首页 · 英语学习中心 · 词库画廊 · 编程打字 · 指法入门 · 天梯榜 · 数据分析 · 班级课堂 · 关于我们
椰程 TypeBuddy 打字搭子 —— 键盘指法练习 · 单词记忆 · 班级课堂 · 在线 PK