读书人

hdu1698Just a Hook (线段树 成段更新

发布时间: 2013-10-06 18:25:14 作者: rapoo

hdu1698Just a Hook (线段树 成段更新,这题目真是坑,按题目意思开的数组还小)
Problem Description

Now Pudge wants to do some operations on the hook.

Let us number the consecutive metallic sticks of the hook from 1 to N. For each operation, Pudge can change the consecutive metallic sticks, numbered from X to Y, into cupreous sticks, silver sticks or golden sticks.
The total value of the hook is calculated as the sum of values of N metallic sticks. More precisely, the value for each kind of stick is calculated as follows:

For each cupreous stick, the value is 1.
For each silver stick, the value is 2.
For each golden stick, the value is 3.

Pudge wants to know the total value of the hook after performing the operations.
You may consider the original hook is made up of cupreous sticks.
InputOutputSample InputSample Output#include<iostream>#include<stdio.h>using namespace std;#define N 200000struct stick{ int sum,z,v;//sum为当前段的总和,z为stick的种类,v为当前段的stick种类是否单一}node[10*N];int p,q,z;void set_tree(int l,int r,int k)//以z=1,每个点种类单一,一开始建线段树,l和r是第k段的左端点和右端点{ int m=(l+r)/2; node[k].sum=r-l+1; node[k].z=1; node[k].v=1; if(l==r) return ; set_tree(l,m,2*k); set_tree(m+1,r,2*k+1);}//-----------更新段p~q段的值-------------void chang_p_to_q(int l,int r,int k)//计更新算出第k个段的值,l和r是第k段的左端点和右端点{ int m=(l+r)/2; if(node[k].z==z) return ;//表明第k段不用更新 if(p<=l&&r<=q)//当第k段在修改的范围内时 { node[k].z=z; node[k].v=1;//第k段的stick为z,stick种类单一 node[k].sum=z*(r-l+1);//计算第k段的总值 //printf("%d~%d:%d(z=%d) ",l,r,node[k].sum,z); return ; } if(node[k].v){//当第k个段stick的种类单一时,左右子树也一定单一,必定会先更新左右子树 node[2*k].z=node[2*k+1].z=node[k].z; //左右子树 node[2*k].v=node[2*k+1].v=1; //左右子树的stick种类单一 node[2*k].sum=(m-l+1)*node[2*k].z;//计算第k段的左子树的总值 node[2*k+1].sum=(r-m)*node[2*k+1].z;//计算第k段的右子树的总值 } if(q<=m){ //要 更新的段 在左子树 node[k*2+1].sum=node[k].sum-node[2*k].sum;//先计算出右子树的总值 chang_p_to_q(l,m,2*k); //计算出左子树的值 } else if(p>m){ //要 更新的段 在右子树 node[k*2].sum=node[k].sum-node[2*k+1].sum; chang_p_to_q(m+1,r,2*k+1); } else { //要 更新的段 在左右子树 chang_p_to_q(l,m,2*k); chang_p_to_q(m+1,r,2*k+1); } node[k].v=0;//第k段的stick种类不单一 node[k].sum=node[k*2].sum+node[k*2+1].sum;//计算第k段的总值 //printf("%d~%d:%d(%d,%d,z=%d) ",l,r,node[k].sum,node[k*2].sum,node[2*k+1].sum,node[k].z);}int main(){ int t,n,m; scanf("%d",&t); for(int i=1;i<=t;i++) { scanf("%d%d",&n,&m); set_tree(1,n,1); while(m--) { scanf("%d%d%d",&p,&q,&z); chang_p_to_q(1,n,1); } printf("Case %d: The total value of the hook is %d.\n",i,node[1].sum); }}

读书人网 >编程

热点推荐