1 条题解
-
0
练61.3 文体两开花
解题思路
保存文学名单顺序,用set保存体育名单。按文学名单逐个查询是否也在体育集合,存在则输出。
正确性说明
按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。
易错点
不能把交集排序输出,必须保留文学名单顺序。
复杂度
时间O((n+m)log m),空间O(n+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; vector<long long> a(n); for (auto &x : a) cin >> x; set<long long> sport; while (m--) { long long x; cin >> x; sport.insert(x); } bool first = true; for (long long x : a) if (sport.count(x)) { if (!first) cout << " "; cout << x; first = false; } cout << "\n"; return 0; }
- 1