POJ 3468 A Simple Problem with Integers【线段树】
A Simple Problem with Integers
Problem Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
Sample Output
4
55
9
15
题解
首先需要注意数据,应该用longlong
其次只有一组测试样例,用while就会WA
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
//#include<bits/stdc++.h>
#define inf 0x3f3f3f3f;
#define ll long long
const int maxn =200005;
using namespace std;
struct node
{
ll l,r,w,f;
}tree[maxn<<2];
ll n,m;
ll q,x,y;
ll ans ;
ll a,b;
int T,kase =0;
void build(int l ,int r ,int k)
{
tree[k].l = l; tree[k].r = r;
if(l==r) {scanf("%lld",&tree[k].w);return ;}
int m = (l+r)/2;
build(l,m,k*2);
build(m+1,r,k*2+1);
tree[k].w = tree[k*2].w + tree[k*2+1].w;
}
void down(int k) //下传标记
{
tree[k*2].f+=tree[k].f;
tree[k*2+1].f+=tree[k].f;
tree[k*2].w+=tree[k].f*(tree[k*2].r-tree[k*2].l+1);
tree[k*2+1].w+=tree[k].f*(tree[k*2+1].r-tree[k*2+1].l+1);
tree[k].f = 0;
}
void sum(int k)
{
if(a<= tree[k].l && tree[k].r<=b)
{
ans+=tree[k].w;
return ;
}
if(tree[k].f) down(k);
int m = (tree[k].l+tree[k].r)/2;
if(a<=m) sum(k*2);
if(b>m) sum(k*2+1);
}
void add(int k)
{
if(tree[k].l>=a&&tree[k].r<=b)//当前区间全部对要修改的区间有用
{
tree[k].w+=(tree[k].r-tree[k].l+1)*x;//(r-1)+1区间点的总数
tree[k].f+=x;
return;
}
if(tree[k].f) down(k);//懒标记下传。只有不满足上面的if条件才执行,所以一定会用到当前节点的子节点
int m=(tree[k].l+tree[k].r)/2;
if(a<=m) add(k*2);
if(b>m) add(k*2+1);
tree[k].w=tree[k*2].w+tree[k*2+1].w;//更改区间状态
}
int main()
{
//scanf("%d",&T);
scanf("%lld%lld",&n,&m);
/printf("Case %d:\n",++kase);
//scanf("%d",&n);
build(1,n,1);
while(m--)
{
char ch[5];
scanf("%s",ch);//如果用 "%c" 就会WA
ans = 0;
if(ch[0]=='Q'){ scanf("%lld%lld",&a,&b); sum(1); printf("%lld\n",ans);}
else if(ch[0] == 'C') { scanf("%lld%lld%lld",&a,&b,&x);add(1);}
}
}

浙公网安备 33010602011771号