C - Kaiten Sushi 解説 by en_translator
Let \(K=\max B_i\).
Before explaining the actual solution, let us consider what will happen when sushi of deliciousness \(1,2,\dots,K\), one each, are supplied. Then, the following happens for \(i=1,2,\dots,N\):
- Person \(i\) takes all the sushi of deliciousness \(A_i\) or greater and eat them. The next person \(i+1\) will meet sushi of deliciousness \(1,2,\dots,A_i-1\), one each.
Let \(\text{id}_i\) be the ID of the person who will eat sushi of deliciousness \(i\) (or \(-1\) if nobody eats it). (Here we use the fact that sushi of the same deliciousness will always be eaten by the same person.) Based on the claim in the paragraph above, it turns out that we can find \(\text{id}_1,\text{id}_2,\dots,\text{id}_K\) as follows:
- Prepare a variable \(r\) initialized with \(r\leftarrow K\).
- For each \(i=1,2,\dots,N\) in order:
- if \(A_i \leq r\), set \(\text{id}_j \leftarrow i\) for each \(j=A_i,A_i+1,\dots,r\), and set \(r\leftarrow A_i-1\).
- for each \(j=1,2,\dots,r\), set \(\text{id}_j \leftarrow -1\).
Once we obtain all of \(\text{id}_1,\text{id}_2,\dots,\text{id}_K\), the person ID who eats sushi of deliciousness \(B_i\ (1\leq i\leq M)\) can be found by simply referring to the value \(\text{id}_{B_i}\).
Hence, the problem has been solved in a total of \(O(N+M+\max B_i)\) time.
Sample code (C++):
#include <bits/stdc++.h>
using namespace std;
const int K = 200010;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> id(K, -1);
int r = K;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
while (r > a) {
--r;
id[r] = i + 1;
}
}
for (int i = 0; i < m; i++) {
int b;
cin >> b;
cout << id[b] << '\n';
}
}
投稿日時:
最終更新: