C - Sushi 解説 by en_translator
We can swap with a lighter neta without making the answer worse, so we may assume lighter netas first.
If netas of weights \(b_1 \leq b_2 \leq \ldots \leq b_t\) are used for sushi and a shari of weight \(a_i\) is paired with a neta of weight \(b_i\), we may assume that \(a_1 \leq a_2 \leq \ldots \leq a_t\). This is because, if \(a_i > a_{i + 1}\), then if \(2a_i \geq b_i\) and \(2a_{i + 1} \geq b_{i + 1}\) then \(2a_{i+1} \geq b_i\) and \(2a_i \geq b_{i+1}\), so one may swap \(a_i\) and \(a_{i+1}\) as long as there exists \(i\) with \(a_i > a_{i + 1}\).
Therefore, the following greedy algorithm is valid: inspecti the netas in order of their weights, and pair it to a shari if there exists a shari that can be paired.
This can be done by sorting \(A\) and \(B\) in ascending order, and applying the sliding window trick. The time complexity is \(O(N \log N + M \log M)\), where sorting is the bottleneck.
Sample code
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int> a(n), b(m);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < m; i++) cin >> b[i];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int x = 0, ans = 0;
for (int i = 0; i < m; i++) {
while (x < n && a[x] * 2 < b[i]) x++;
if (x < n) {
x++;
ans++;
}
}
cout << ans << '\n';
}
投稿日時:
最終更新: