【CODEFORCES】 B. Worms

2998 단어 codeforces이분
B. Worms
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.
Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.
Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.
Input
The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile.
The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot.
The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.
Output
Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.
Sample test(s)
input
5
2 7 3 4 9
3
1 25 11

output
1
5
3

Note
For the sample input:
The worms with labels from [1, 2] are in the first pile.
The worms with labels from [3, 9] are in the second pile.
The worms with labels from [10, 12] are in the third pile.
The worms with labels from [13, 16] are in the fourth pile.
The worms with labels from [17, 25] are in the fifth pile.
문제풀이: 이 문제는 접두사 그룹을 합친 후 2분 동안 찾는 것이다.아무리 폭력적이어도 지나갈 수 있을 것 같은데..
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int a[100005],n,q,m,sum[100005];

void find(int k,int low,int high)
{
    int l=low,r=high,t=(l+r)/2;
    while (r!=l)
    {
        t=(l+r)/2;
        if (sum[t]==k)
        {
            printf("%d
",t); break; } else if (r-1==l) { printf("%d
",r); break; } else if (sum[t]>k) r=t; else if (sum[t]<k) l=t; } return ; } int main() { scanf("%d",&n); for (int i=0;i<n;i++) scanf("%d",&a[i]); sum[0]=0; for (int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i-1]; scanf("%d",&m); while (m--) { scanf("%d",&q); find(q,0,n); } return 0; }

좋은 웹페이지 즐겨찾기