update是为了优化线段树的时间问题。
update是一个标志,表示在它下面的儿子、孙子、曾孙们需不需要改变。当它为true时,说明下面子孙待更新;为false时,说明它下面子孙的状态都是最新的。它的作用是为了尽量不更新它的子孙,从而缩短总时间。
例题:(来源 poj 2777)
有L段线段(编号为1~L) ,一开始全部是第1种颜色。有两种操作
1、C A B tt :A~B染第tt种颜色
2、P A B :询问A~B有多少种不一样的颜色。
思路:线段树update优化+状态压缩。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
int l,r,lc,rc,c;
bool update;
}tr[200010];int len;
char s[5];
int col(int x)//计算二进制数x中1的个数
{
int ans=0;
while(x>0)
{
ans+=x%2;
x>>=1;
}
return ans;
}
void bt(int l,int r)
{
len++;int now=len;
tr[now].l=l;tr[now].r=r;tr[now].lc=tr[now].rc=-1;tr[now].c=1;
tr[now].update=false;//开始都是最新的,不需要更新
if(l<r)
{
int mid=(l+r)/2;
tr[now].lc=len+1; bt(l,mid);
tr[now].rc=len+1; bt(mid+1,r);
}
}
void update(int now)//update的状态转移
{
tr[now].update=false;
tr[tr[now].lc].update=true;
tr[tr[now].lc].c=tr[now].c;
tr[tr[now].rc].update=true;
tr[tr[now].rc].c=tr[now].c;
}
void change(int now,int l,int r,int k)
{
if(tr[now].l==l&&tr[now].r==r)
{
tr[now].c=k;
tr[now].update=true;
return ;
}
int lc=tr[now].lc,rc=tr[now].rc;
int mid=(tr[now].l+tr[now].r)/2;
if(tr[now].update) update(now);//要用到它子孙的信息了,不得不更新
if(r<=mid) change(lc,l,r,k);
else if(mid+1<=l) change(rc,l,r,k);
else
{
change(lc,l,mid,k);
change(rc,mid+1,r,k);
}
tr[now].c=tr[lc].c|tr[rc].c;
}
int wen(int now,int l,int r)
{
if(tr[now].l==l&&tr[now].r==r) return tr[now].c;
int lc=tr[now].lc,rc=tr[now].rc;
int mid=(tr[now].l+tr[now].r)/2;
if(tr[now].update) update(now);//要用到它子孙的信息了,不得不更新
if(r<=mid) return wen(lc,l,r);
else if(mid+1<=l) return wen(rc,l,r);
else return wen(lc,l,mid)|wen(rc,mid+1,r);
}
int main()
{
int l,t,m;
while(scanf("%d%d%d",&l,&t,&m)!=EOF)
{
len=0;bt(1,l);
while(m--)
{
int x,y,k;
scanf("%s",s);
if(s[0]=='C')
{
scanf("%d%d%d",&x,&y,&k);
if(x>y) swap(x,y);
change(1,x,y,1<<(k-1));//1<<(k-1)用了状压,意思是第k种颜色已涂上
}
else
{
scanf("%d%d",&x,&y);
if(x>y) swap(x,y);
int ans=wen(1,x,y);
printf("%d\n",col(ans));
}
}
}
return 0;
}
推荐:《线段树—初始化与更改、查询》http://blog.csdn.net/a_bright_ch/article/details/54410757
《线段树—离散化压缩空间优化》http://blog.csdn.net/a_bright_ch/article/details/54472802
《线段树—倒推优化》http://blog.csdn.net/a_bright_ch/article/details/54617401