题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1698
解题思路:
方法1:每次操作将一段区间的值都修改为同一个值,最后求整个区间的总和。看做区间修改,区间求和的模型
方法2:每次将区间修改为一种颜色。看做染色与覆盖的问题。
代码1:
#include<cstdio>
#include<cstring>
#include<algorithm>
#define mid int m = l+r>>1;
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
using namespace std;
const int N = 1e5+5;
int tree[N<<2],lazy[N<<2];
void push_up(int rt)
{
tree[rt] = tree[rt<<1] + tree[rt<<1|1];
}
void push_down(int rt,int len)
{
tree[rt<<1] = lazy[rt]*(len-len/2);
tree[rt<<1|1] = lazy[rt]*(len/2);
lazy[rt<<1] = lazy[rt];
lazy[rt<<1|1] = lazy[rt];
lazy[rt] = 0;
}
void update(int L,int R,int x,int rt,int l,int r)
{
if (L<=l && r<=R){
tree[rt] = x*(r-l+1);
lazy[rt] = x;
return ;
}
if (lazy[rt]) push_down(rt,r-l+1);
mid;
if (L<=m) update(L,R,x,lson);
if (R>m) update(L,R,x,rson);
push_up(rt);
}
int query(int L,int R,int rt,int l,int r)
{
if (L<=l && r<=R){
return tree[rt];
}
if (lazy[rt]) push_down(rt,r-l+1);
mid;
int ans = 0;
if (L<=m) ans += query(L,R,lson);
if (R>m) ans += query(L,R,rson);
return ans;
}
void build(int rt,int l,int r)
{
if (l==r){
tree[rt] = 1;
return ;
}
mid;
build(lson);
build(rson);
push_up(rt);
}
int main()
{
int t,n,q,x,y,v,ica=0;
scanf("%d",&t);
while (t--){
memset(lazy,0,sizeof lazy);
scanf("%d %d",&n,&q);
build(1,1,n);
while (q--){
scanf("%d %d %d",&x,&y,&v);
update(x,y,v,1,1,n);
}
printf("Case %d: The total value of the hook is %d.\n",++ica,query(1,n,1,1,n));
}
return 0;
}
代码2:(不是同一时间写的,风格有点出入)
#include<cstdio>
#include<cstring>
#include<algorithm>
#define lson rt<<1,l,m
#define rson rt<<1|1,m+1,r
#define mid int m=l+r>>1
#define tl tree[rt<<1]
#define tr tree[rt<<1|1]
using namespace std;
const int N = 1e5+5;
int tree[N<<2];
void push_down(int rt)
{
tl = tr = tree[rt];
}
void push_up(int rt)
{
if (tl==tr) tree[rt] = tl;
else tree[rt] = -1;
}
void update(int L,int R,int x,int rt,int l,int r)
{
if (L<=l && r<=R){
tree[rt] = x;
return ;
}
if (tree[rt]>0) push_down(rt);
mid;
if (L<=m) update(L,R,x,lson);
if (R>m) update(L,R,x,rson);
push_up(rt);
}
int query(int rt,int l,int r)
{
if (tree[rt]>0){
return tree[rt]*(r-l+1);
}
mid;
int ans = 0;
ans += query(lson);
ans += query(rson);
return ans;
}
void init(int rt,int l,int r)
{
if (l==r){
tree[rt] = 1;
return ;
}
mid;
init(lson);
init(rson);
push_up(rt);
}
int main()
{
int t,n,q,x,y,v;
scanf("%d",&t);
int ica = 1;
while (t--){
scanf("%d",&n);
init(1,1,n);
scanf("%d",&q);
while (q--){
scanf("%d %d %d",&x,&y,&v);
if (x>y) swap(x,y);
update(x,y,v,1,1,n);
}
printf("Case %d: The total value of the hook is %d.\n",ica++,query(1,1,n));
}
return 0;
}