1 条题解
-
0
【例66.2】 朋友关系
解题思路
用名字到朋友集合的map保存无向关系,每对双方都加入对方。遍历各集合大小取最大,不扩展间接朋友。
正确性说明
依题目给出的对应关系逐项处理,位置与原输入保持明确对应。每一步完成当前项的全部贡献,结束后得到所有位置或字符的目标结果。
易错点
朋友关系不传递;集合可消除重复关系,孤立学生度数0。
复杂度
时间O(m log m),空间O(m)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n, m; cin >> n >> m; map<string, set<string>> g; while (m--) { string a, b; cin >> a >> b; g[a].insert(b); g[b].insert(a); } size_t ans = 0; for (auto &p : g) ans = max(ans, p.second.size()); cout << ans << "\n"; return 0; }
- 1