Title description
FJ is going to teach his cow to play a song. The song is composed of N (1 <= N <= 50,000) syllables, numbered 1 to N, and must be played in order from 1 to N, the i The syllable lasts B_i (1 <= B_i <= 10,000) beats, the beats are counted from 0, so the first syllable is played from beat 0 to beat B_1-1, from B_1 to B_1 + B_2-1 It is the second syllable, and so on.
Recently cows are not interested in playing the piano, they feel too boring. So in order to keep the cows focused, FJ asked Q (1 <= Q <= 50,000) questions, the format of the question is "what syllable is played in the Tth beat",
each question corresponds to a T_i (0 <= T_i <= Total number of beats-1) Please help the cow to solve it.
Input
In the first line, enter two space-separated integers N and Q.
Lines 2 to N + 1 each line contains an integer B_i line
N + 2-N + Q + 1 line each line contains an integer T_i
Output
The output has Q lines, and each line outputs the answer to the corresponding question.
Sample input
3 5
2
1
3
2
3
4
0
1
Sample output
2
3
3
1
1
analysis
Violence is easy to think about, but it times out.
Positive solution: Find the a [x] binary after the a array prefix and the binary search, and output mid or l.
Code on
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,q,a[100001];
int main()
{
freopen("mnotes.in","r",stdin);
freopen("mnotes.out","w",stdout);
cin>>n>>q;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
a[i]=a[i-1]+a[i];//前缀和
}
for(register int i=1;i<=q;i++)
{
int x;
scanf("%d",&x);
x++;
int l=1,r=n,ff=0,mid;
while(l<=r)//二分找a[x]
{
mid=(l+r)/2;
if(a[mid]>x)
{
r=mid-1;
}
if(a[mid]<x)
{
l=mid+1;
}
if(a[mid]==x)
{
printf("%d\n",mid);
ff=1;
break;
}
}
if(!ff) printf("%d\n",l);
}
fclose(stdin);
fclose(stdout);
return 0;
}