1 条题解
-
0
【例64.2】 生日相同
解题思路
以(月,日)为map键分组名字,map自然按日期排序。仅输出人数≥2的组,组内按长度升序、同长字典序排序。
正确性说明
依题目给出的对应关系逐项处理,位置与原输入保持明确对应。每一步完成当前项的全部贡献,结束后得到所有位置或字符的目标结果。
易错点
没有任何重复日期才输出None,不是只看相邻输入。
复杂度
n名、名字长度L,时间O(nL log n),空间O(nL)。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; map<pair<int, int>, vector<string>> g; while (n--) { string s; int m, d; cin >> s >> m >> d; g[{m, d}].push_back(s); } bool any = false; for (auto &kv : g) if (kv.second.size() >= 2) { any = true; auto &v = kv.second; sort(v.begin(), v.end(), [](const string &a, const string &b) { if (a.size() != b.size()) return a.size() < b.size(); return a < b; }); cout << kv.first.first << " " << kv.first.second; for (auto &s : v) cout << " " << s; cout << "\n"; } if (!any) cout << "None\n"; return 0; }
- 1