HDU 1698 Just a Hook(线段树:区间set,区间查询)
http://acm.hdu.edu.cn/showproblem.php?pid=1698
题意:
Problem Description
In the game of DotA, Pudge’s meat hook is actually the most horrible thing for most of the heroes. The hook is made up of several consecutive metallic sticks which are of the same length.
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.
Input
The input consists of several test cases. The first line of the input is the number of the cases. There are no more than 10 cases.
For each case, the first line contains an integer N, 1<=N<=100,000, which is the number of the sticks of Pudge’s meat hook and the second line contains an integer Q, 0<=Q<=100,000, which is the number of the operations.
Next Q lines, each line contains three integers X, Y, 1<=X<=Y<=N, Z, 1<=Z<=3, which defines an operation: change the sticks numbered from X to Y into the metal kind Z, where Z=1 represents the cupreous kind, Z=2 represents the silver kind and Z=3 represents the golden kind.
分析:
线段树区间set基本操作,详情看刘汝佳训练指南。
AC代码:
//HDU 1698 线段树 区间set 区间查询
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define lson i*2,l,m
#define rson i*2+1,m+1,r
const int MAXN=100000+100;
int sum[MAXN*4];
int setv[MAXN*4];
void PushUp(int i)
{
sum[i]=sum[i*2]+sum[i*2+1];
}
void PushDown(int i,int num)
{
if(setv[i])
{
setv[i*2]=setv[i*2+1]=setv[i];
sum[i*2]=(num-num/2)*setv[i];//分num为奇数和偶数情况讨论
sum[i*2+1]=(num/2)*setv[i];
setv[i]=0;
}
}
void build(int i,int l,int r)
{
setv[i]=0;
sum[i]=1;
if(l==r) return ;//注意这里
int m=(l+r)/2;
build(lson);
build(rson);
PushUp(i);
}
void update(int ql,int qr,int v,int i,int l,int r)
{
if(ql<=l&&r<=qr)
{
setv[i]=v;
sum[i]=v*(r-l+1);
return;
}
PushDown(i,r-l+1);//注意这里
int m=(r+l)/2;
if(ql<=m)update(ql,qr,v,lson);
if(qr>m)update(ql,qr,v,rson);
PushUp(i);
}
int query(int ql,int qr,int i,int l,int r)
{
if(ql<=l&&r<=qr)
{
return sum[i];
}
PushDown(i,r-l+1);//注意这里
int m=(r+l)/2;
int res=0;
if(ql<=m) res +=query(ql,qr,lson);
if(m<qr) res+=query(ql,qr,rson);
return res;
}
int main()
{
int T;
scanf("%d",&T);
for(int kase=1;kase<=T;kase++)
{
int n,q;
scanf("%d%d",&n,&q);
build(1,1,n);
while(q--)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
update(x,y,z,1,1,n);
}
printf("Case %d: The total value of the hook is %d.\n",kase,query(1,n,1,1,n));
}
return 0;
}