思路
维护一个最大堆(因为如果是最小堆取前n个的话会爆m),只需要判断:如果堆中元素个数小于n,入堆;如果大于n,并且堆顶的元素(堆中元素最大值)比当前元素大,那么就说明找到一个更小的,入堆,反之继续判断下一个
因为数列是单调不减的,所以当 a 中的数遍历完之后都没有入队的,那么后面的就肯定不可能再入堆了
(这道题和另外一道黄题 P2085 最小函数值 的区别就在于会多卡一手时间,原因见上,买一送一了属于是)
小技巧:
用 static_cast<int> 将 size_t 类型的转换成 int
1
| if(static_cast<int>(pq.size()) < n)
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include<bits/stdc++.h> #define int long long #define endl '\n' using namespace std;
signed main(){ ios::sync_with_stdio(false); cin.tie(0),cout.tie(0); int n; cin >> n; vector<int> a(n); vector<int> b(n); for(int i = 0 ; i < n ; i ++){ cin >> a[i]; } for (int i = 0; i < n; i++) { cin >> b[i]; } priority_queue<int> pq; for(int i = 0 ; i < n ; i++){ bool f = false; for(int j = 0 ; j < n ;j++){ int x = a[i] + b[j]; if(static_cast<int>(pq.size()) < n){ f = true; pq.emplace(x); } else if(pq.top() > x){ f = true; pq.pop(); pq.emplace(x); } } if(!f){ break; } } vector<int> re; while(!pq.empty()){ re.push_back(pq.top()); pq.pop(); } for(int i = n - 1 ; i >= 0 ; i--){ cout << re[i] << " "; } cout << endl; return 0; }
|