题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1698
思路:updata()区间替换,query()区间求和
先上3篇博客 1:http://blog.sina.com.cn/s/blog_a2dce6b30101l8bi.html
2:http://www.tuicool.com/articles/j6N3eaz
因为每次都更新到最下面会很费时间,所有有了懒惰标记
就是每次更新不更新到最后..而是更新到包含了区间的最大的节点.
然后如果下次更新的时候更新到了上次已经更新到的节点..
那先把上次更新暂停的节点往下更新..直到这次更新的区间最大的节点没有被标记..
因为没必要都更新只要更新到需要的程度就可以了(查询或者更新节点)
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long ll;
const int maxn = 100010;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int sum[maxn<<2];
int value[maxn<<2];
void pushup(int rt)
{
sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void pushdown(int rt,int m)
{
if(value[rt])
{
value[rt<<1] = value[rt<<1|1] = value[rt];
sum[rt<<1] = (m - (m>>1)) * value[rt];//左节点的数目总是比右节点的数目多一个或者相等
sum[rt<<1|1] = (m>>1) * value[rt];
value[rt] = 0;//增量已经传递了,所以要变为0
}
}
void build(int l,int r,int rt)
{
value[rt] = 0;
sum[rt] = 1;
if(l == r) return;
int m = (l + r) >> 1;
build(lson);
build(rson);
pushup(rt);
}
void updata(int L,int R,int c,int l,int r,int rt)
{
if(l >= L && r <= R)
{
value[rt] = c;
sum[rt] = (r - l + 1) * c;
return;
}
pushdown(rt,r-l+1);//里面的参数要写对
int m = (l + r) >> 1;
if(L <= m) updata(L,R,c,lson);
if(R > m) updata(L,R,c,rson);
pushup(rt);
}
int main()
{
int t,n,m;
scanf("%d",&t);
for(int cas=1; cas<=t; cas++)
{
scanf("%d%d",&n,&m);
build(1,n,1);
for(int i=0; i<m; i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
updata(x,y,z,1,n,1);
}
printf("Case %d: The total value of the hook is %d.\n",cas,sum[1]);
}
return 0;
}