2024-03 · 7级 · 交流问题
CCF 原卷官方标程 · 数组与向量、STL、位运算、搜索 · 本地编译通过
正文
// 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 标程 · 考级真题的其它内容
- 2026-09 · 1级 · 新龟兔赛跑
- 2026-09 · 1级 · 棋盘上的奖赏
- 2026-06 · 1级 · 去旅行
- 2026-06 · 1级 · 交税
- 2026-03 · 1级 · 交朋友
- 2026-03 · 1级 · 数字替换
- 2025-12 · 1级 · 小杨的爱心快递
- 2025-12 · 1级 · 手机电量显示
- 2025-09 · 1级 · 商店折扣
- 2025-09 · 1级 · 金字塔
- 2025-06 · 1级 · 假期阅读
- 2025-06 · 1级 · 值日
- 2025-03 · 1级 · 编程题 1
- 2025-03 · 1级 · 编程题 2
- 2024-12 · 1级 · 温度转换
- 2024-12 · 1级 · 奇数和偶数
- 2024-09 · 1级 · 小杨购物
- 2024-09 · 1级 · 美丽数字
- 2024-06 · 1级 · 休息时间
- 2024-06 · 1级 · 立方数
- 2024-03 · 1级 · 小杨买书
- 2024-03 · 1级 · 找因数
- 2023-12 · 1级 · 小杨的考试
- 2023-12 · 1级 · 小杨报数
- 2023-09 · 1级 · 买文具
- 2023-09 · 1级 · 小明的幸运数
- 2023-06 · 1级 · 时间规划
- 2023-06 · 1级 · 累计相加
- 2023-03 · 1级 · 每月天数
- 2023-03 · 1级 · 长方形面积
- 2026-09 · 2级 · 直角三角形
- 2026-09 · 2级 · 字符变换
- 2026-06 · 2级 · 完全平方数计数
- 2026-06 · 2级 · 菱形
- 2026-03 · 2级 · 数数
- 2026-03 · 2级 · 画画
- 2025-12 · 2级 · 环保能量球
- 2025-12 · 2级 · 黄金格
- 2025-09 · 2级 · 优美的数字
- 2025-09 · 2级 · 菱形
- 2025-06 · 2级 · 数三角形
- 2025-06 · 2级 · 幂和数
- 2025-03 · 2级 · 编程题 1
- 2025-03 · 2级 · 时间跨越
- 2024-12 · 2级 · 寻找数字
- 2024-12 · 2级 · 数位和
- 2024-09 · 2级 · 数位之和
- 2024-09 · 2级 · 小杨的
- 2024-06 · 2级 · 平方之和
- 2024-06 · 2级 · 计数
- 2024-03 · 2级 · 乘法问题
- 2024-03 · 2级 · 小杨的日字矩阵
- 2023-12 · 2级 · 小杨做题
- 2023-12 · 2级 · 小杨的 H 字矩阵
- 2023-09 · 2级 · 小杨的 X 字矩阵
- 2023-09 · 2级 · 数字黑洞
- 2023-06 · 2级 · 找素数
- 2023-06 · 2级 · 自幂数判断
- 2023-03 · 2级 · 画三角形
- 2023-03 · 2级 · 百鸡问题