题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698
很简单的一个线段树的题目,每次更新采用lazy思想,这里我采用了增加一个变量z,z不等于0时其绝对值表示当前区间的牌的性质并且代表更新到此区间
代码:
1 #include<iostream> 2 #include<cstdlib> 3 #include<cstring> 4 #include<cstdio> 5 using namespace std; 6 #define maxn 100010 7 class node 8 { 9 public: 10 int l; 11 int r; 12 int sum; 13 int z; 14 }; 15 int n; 16 int q; 17 int x,y,z; 18 node segTree[maxn*3]; 19 void build(int num, int l,int r) 20 { 21 segTree[num].l=l; 22 segTree[num].r=r; 23 segTree[num].z=0; 24 if(l==r) 25 { 26 segTree[num].sum=1; 27 return ; 28 } 29 int mid=(l+r)/2; 30 build(num*2,l,mid); 31 build(num*2+1,mid+1,r); 32 segTree[num].sum=segTree[num*2].sum+segTree[num*2+1].sum; 33 } 34 void Update(int num,int l,int r,int z) 35 { 36 if(segTree[num].l ==l && segTree[num].r ==r) 37 { 38 segTree[num].z=z; 39 segTree[num].sum=(segTree[num].r- segTree[num].l +1)*segTree[num].z; 40 return ; 41 } 42 int mid=(segTree[num].l + segTree[num].r)/2; 43 if(segTree[num].z) 44 { 45 Update(num*2,segTree[num].l,mid,segTree[num].z); 46 Update(num*2+1,mid+1,segTree[num].r,segTree[num].z); 47 segTree[num].z=0; 48 } 49 50 if(r<=mid) 51 Update(num*2,l,r,z); 52 else if(l>mid) Update(num*2+1,l,r,z); 53 else 54 { 55 Update(num*2,l,mid,z); 56 Update(num*2+1,mid+1,r,z); 57 } 58 segTree[num].sum = segTree[num*2].sum + segTree[num*2+1].sum; 59 } 60 int main() 61 { 62 int t; 63 scanf("%d",&t); 64 int iCase=1; 65 while(t--) 66 { 67 scanf("%d%d",&n,&q); 68 build(1,1,n); 69 for(int i=0;i<q;i++) 70 { 71 scanf("%d%d%d",&x,&y,&z); 72 Update(1,x,y,z); 73 } 74 cout<<"Case "<<iCase++<<":"<<" The total value of the hook is "<<segTree[1].sum<<"."<<endl; 75 76 } 77 return 0; 78 }