题意:一个长度为n的数组,开始时价值均为1,之后有m次操作,修改一定区间的价值(1-3),最后求总价值
思路:lazy的思想:每次处理的时候不需要修改到最根部,只需要修改到某个区间,每次都判断一下该区间是否是杂色的。杂色的在下次的访问的时候会修改子区间的值
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#define N 100005
#define l(x) x<<1
#define r(x) (x<<1)|1
#define MID(x,y) ((x+y)>>1)
using namespace std;
int n,m;
int ans;
struct Node
{
int l,r;
int p;
};
Node node[N<<2];
void built(int t,int l,int r)
{
node[t].l=l;
node[t].r=r;
node[t].p=1;
if(l==r) return;
built(l(t),l,MID(l,r));
built(r(t),MID(l,r)+1,r);
}
void update(int t,int l,int r,int p)
{
if(node[t].l==l && node[t].r==r)
{
node[t].p=p;
return;
}
int mid=MID(node[t].l,node[t].r);
if(node[t].p!=0){
node[l(t)].p=node[r(t)].p=node[t].p;
node[t].p=0;
}
if(r<=mid) update(l(t),l,r,p);
else if(l>mid) update(r(t),l,r,p);
else{
update(l(t),l,mid,p);
update(r(t),mid+1,r,p);
}
if(node[l(t)].p==node[r(t)].p && node[l(t)].p!=0) node[t].p=node[l(t)].p;
else node[t].p=0;
}
void result(int t)
{
if(node[t].p) {
ans+=(node[t].r-node[t].l+1)*node[t].p;
return;
}
result(l(t));
result(r(t));
}
int main()
{
int t;
int num=1;
int p,q,r;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
built(1,1,n);
while(m--)
{
scanf("%d %d %d",&p,&q,&r);
update(1,p,q,r);
}
ans=0;
result(1);
printf("Case %d: The total value of the hook is %d.\n",num++,ans);
}
return 0;
}