NC24866 [USACO 2009 Dec S]Music Notes
题目
题目描述
FJ is going to teach his cows how to play a song. The song consists of N (1 <= N <= 50,000) notes, and the i-th note lasts for Bi (1 <= Bi <= 10,000) beats (thus no song is longer than 500,000,000 beats). The cows will begin playing the song at time 0; thus, they will play note 1 from time 0 through just before time B1, note 2 from time B1 through just before time B1 + B2, etc.
However, recently the cows have lost interest in the song, as they feel that it is too long and boring. Thus, to make sure his cows are paying attention, he asks them Q (1 <= Q <= 50,000) questions of the form, "In the interval from time T through just before time T+1, which note should you be playing?" The cows need your help to answer these questions which are supplied as Ti (0 <= Ti <= end_of_song).
Consider this song with three notes of durations 2, 1, and 3 beats:
Beat: 0 1 2 3 4 5 6 ...
|----|----|----|----|----|----|--- ...
1111111111 : :
22222: :
333333333333333:
Here is a set of five queries along with the resulting answer:
Query Note
2 2
3 3
4 3
0 1
1 1
输入描述
* Line 1: Two space-separated integers: N and Q
* Lines 2..N+1: Line i+1 contains the single integer: Bi
* Lines N+2..N+Q+1: Line N+i+1 contains a single integer: Ti
输出描述
* Lines 1..Q: Line i of the output contains the result of query i as a single integer.
示例1
输入
3 5
2
1
3
2
3
4
0
1
输出
2
3
3
1
1
题解
知识点:二分。
先做前缀和得到每个音符的终止位置,发现音符 \(i\) 出现在 \([sum_{i-1},sum_{i})\) 。要查找 \([T,T+1)\) 区间的音符,于是二分查找第一个位置 \(i\) 使得 \(sum_i>T\) ,就有 \([T,T+1) \subseteq [sum_{i-1},sum_{i})\) 那么 \(i\) 就是答案。
时间复杂度 \(O(q \log n)\)
空间复杂度 \(O(n)\)
代码
#include <bits/stdc++.h>
using namespace std;
int B[50007];
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, q;
cin >> n >> q;
for (int i = 1;i <= n;i++) cin >> B[i], B[i] += B[i - 1];
while (q--) {
int t;
cin >> t;
cout << upper_bound(B + 1, B + n + 1, t) - B << '\n';
}
return 0;
}
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16419049.html