Nyoj soldier Kills (i) 108 (segment tree)

Source: Internet
Author: User
soldier Kills (i)Time limit: Ms | Memory limit: 65535 KB Difficulty: 3 description

South Generals have n soldiers, numbered 1 to N, each of these soldiers is known for their kills.

The boy is the South General's military advisers, the South General now want to know the number M to No. N soldiers total kills, please help the handyman to answer the South General.

Note that the South General may ask many questions. Enter only one set of test data
The first line is two integer n,m, where N represents the number of soldiers (1<n<1000000), and M indicates the number of times the South General inquired (1<M<100000)
The next line is n integers, and AI represents the number of soldier kills. (0<=ai<=100)
The subsequent M-line has two integer m,n per line, indicating that the general South wants to know the total number of kills (1<=m,n<=n) of soldiers from number m to nth.
Output for each query, the total number of kills
Each output takes one line sample input

5 2
1 2 3 4 5
1 3
2 4
Sample output
6
9
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define N 1000010
using namespace std;
int a[n];
struct ZZ
{
	int l;
	int R;
	int m;
} q[n<<2];
void build (int gen,int l,int r)
{
	q[gen].l=l;
	Q[gen].r=r;
	if (l==r)
	{
		q[gen].m=a[l];
		return;
	}
	int mid= (L+R)/2;
	Build (Gen<<1,l,mid);
	Build (gen<<1|1,mid+1,r);
	q[gen].m=q[gen<<1].m+q[gen<<1|1].m;
}
int query (int gen,int l,int r)
{
	if (L<=Q[GEN].L&&R>=Q[GEN].R)
		return q[gen].m;
	int mid= (Q[GEN].L+Q[GEN].R)/2;
	int cnt=0;
	if (l<=mid)
		cnt+=query (gen<<1,l,r);
	if (r>mid)
		cnt+=query (gen<<1|1,l,r);
	return cnt;
}
int main ()
{
	int n,m,i,j,x,y;
	while (scanf ("%d%d", &n,&m)!=eof)
	{
		for (i=1;i<=n;i++)
			scanf ("%d", &a[i]);
		Build (1,1,n);
		while (m--)
		{
			scanf ("%d%d", &x,&y);
			printf ("%d\n", Query (1,x,y));
		}
	}
	return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.