关于线段树以前也有过接触,不过忘了,重新回顾一下,线段树是用二叉树来实现的。
关于线段树的概念,这个blog写的很详细,大家可以看一下http://www.cnblogs.com/shuaiwhu/archive/2012/04/22/2464583.html
hdu 1698 Just A Hook
这题题意是屠夫的钩子为n的长度,每段的材质都可以改变,一开始都是铜材质的,经过q次变化后求钩子的价值。(1表示铜,2表示银,3表示金)我们可以把这题简化成染色问题,给钩子染色,一开始都是1这种颜色,然后用别的颜色覆盖上去,这样比较好理解。一题比较基础的线段树,也不多说,附上代码:
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
const int MAXN=400012;
class node{
public:
int left,right,value;
} a[MAXN];
int maxroot,n,q,i;
int max(int a,int b)
{
if (a>b) return a; else return b;
}
void build(int root,int l,int r)//建树
{
int mid; mid=(l+r)>>1;
maxroot=max(root,maxroot);
a[root].left=l;
a[root].right=r;
a[root].value=1;
if (l==r) return;
build(root*2,l,mid);
build(root*2+1,mid+1,r);
}
void color(int root,int l,int r,int v)//染色,可以说这是用了线段树中的Lazy算法吧
{
if (l<=a[root].left&&a[root].right<=r)
{
a[root].value=v;
}
else{
if (a[root].value!=-1) a[root*2].value=a[root*2+1].value=a[root].value;
a[root].value=-1;
if (l<=a[root*2].right) color(root*2,l,r,v);
if (a[root*2+1].left<=r) color(root*2+1,l,r,v);
}
}
int Count(int root)//计算
{
if (root<=maxroot)
{
if (a[root].value!=-1) return a[root].value*(a[root].right-a[root].left+1);
else return Count(root*2)+Count(root*2+1);
} else return 0;
}
int main()
{
int T,x,y,v;
cin>>T;
for (int I=1;I<=T;I++)
{
scanf("%d",&n);
scanf("%d",&q);
maxroot=1;
build(1,1,n);
for (i=1;i<=q;i++)
{
scanf("%d%d%d",&x,&y,&v);
color(1,x,y,v);
}
cout<<"Case "<<I<<": The total value of the hook is "<<Count(1)<<'.'<<endl;
}
}