1547: [Example 1] interval and

Description [title]

Given a number of columns, there are two provisions of the operation, first modify an element, the second is seeking continuous and interval.

[Enter]

The first line of input data contains two positive integers n, m (n≤100000, m≤500000), the following lines are m,

Each row has three positive integer k, a, b (k = 0 or 1, a, b≤n) .k = 0 indicates the time at a number with b, k = represents interrogation interval [a, b] 1 and all numbers within.

[Output]

For each query output corresponding answers.

[Sample input]

10 20
0 1 10
1 1 4
0 6 6
1 4 10
1 8 9
1 4 9
0 10 2
1 1 8
0 2 10
1 3 9
0 7 8
0 3 10
0 1 1
1 3 8
1 6 9
0 5 5
1 1 8
0 4 2
1 2 8
0 1 1

[Sample Output]

10
6
0
6
16
6
24
14
50
41

【source】

no

Own comments

Segment tree, the tree number is the sum originally divided into several sections, although the calculation itself and reduces efficiency, but adds changes to improve the overall efficiency (weigh on the occasion, said it would not pay attention to change it), in fact, use of dichotomous thinking, not while he was not looking.

#include<cstdio>
using namespace std;
const int N=600001;
long long n,m,c[N]={0},a,b;
bool k;
int qread() {
	char ch=getchar();
	int x=0,f=1;
	while (ch>'9'||ch<'0') {
		if(ch=='-') f=-1;
		ch=getchar();
	}
	while (ch>='0'&&ch<='9') {
		x=(x<<3)+(x<<1)+ch-48;
		ch=getchar();
	}
	return x*f;
}
long long sum (int k,int l,int r,int x,int y) {//求和 
	if(r<x||y<l) return 0;//如果要求的区间与找到的区间交集为空,返回 
	if(l>=x&&y>=r) return c[k];//如果找到的区间包含于要求的区间,返回这个区间的值 
	int mid=(l+r)/2;//剩下的情况即使两者交集不为空,则二分区间继续找 
	return sum(2*k,l,mid,x,y)+sum(2*k+1,mid+1,r,x,y);
}
void add(int k,int l,int r,int x,int v) {//自叶向上 
	if(x<l||x>r) return ;//不在区间内不做操作 
	if(l==r&&r==x) {//找到叶子节点,加上 
		c[k]+=v;
		return;
	}
	int mid=(l+r)/2;//要改的在区间内找叶子节点 
	add(2*k,l,mid,x,v);
	add(2*k+1,mid+1,r,x,v);
	c[k]=c[2*k]+c[2*k+1];//更新值 
}
int main () {
	n=qread();m=qread();
	while (m--) {
		k=qread();a=qread();b=qread();
		if(k) printf("%lld\n",sum(1,1,n,a,b));
		else add(1,1,n,a,b);
	}
	return 0;
}
发布了15 篇原创文章 · 获赞 13 · 访问量 519

Guess you like

Origin blog.csdn.net/weixin_44952985/article/details/104040507