Just a Hook
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 27359 Accepted Submission(s): 13593
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.
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.
把一個區間範圍內的數字全部替換成另一個數字,最後求1-n的數字和,跟一般更新的線段樹不太一樣,這個是替換而不是更新,學習一下別人的寫法。
代碼:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define INF 0x3f3f3f3f
#define MM(x,y) memset(x,y,sizeof(x))
#define LC(x) (x<<1)
#define RC(x) ((x<<1)|1)
#define MID(x,y) ((x+y)>>1)
typedef pair<int,int> pii;
typedef long long LL;
const int N=100010;
struct seg
{
int l,mid,r;
int sum,add;
};
seg T[N<<2];
void pushup(int k)
{
T[k].sum=T[RC(k)].sum+T[LC(k)].sum;
}
void pushdown(int k,int len)//pushdownÇø¼äÌæ»»µÄд·¨
{
if(T[k].add)
{
T[LC(k)].add=T[k].add;
T[RC(k)].add=T[k].add;
T[LC(k)].sum=T[k].add*(len-len/2);
T[RC(k)].sum=T[k].add*(len/2);
T[k].add=0;
}
}
void build(int k,int l,int r)
{
T[k].l=l;
T[k].r=r;
T[k].mid=MID(l,r);
T[k].add=0;
if(l==r)
T[k].sum=1;
else
{
build(LC(k),l,T[k].mid);
build(RC(k),T[k].mid+1,r);
pushup(k);
}
}
void update(int k,int l,int r,int val)
{
if(r<T[k].l||T[k].r<l)
return ;
if(l<=T[k].l&&r>=T[k].r)
{
T[k].add=val;
T[k].sum=val*(T[k].r-T[k].l+1);
}
else
{
pushdown(k,T[k].r-T[k].l+1);
if(l<=T[k].mid)
update(LC(k),l,r,val);
if(r>T[k].mid)
update(RC(k),l,r,val);
pushup(k);
}
}
int main(void)
{
int tcase,i,j,n,m,l,r,val;
scanf("%d",&tcase);
for (int q=1; q<=tcase; ++q)
{
scanf("%d",&n);
build(1,1,n);
scanf("%d",&m);
for (i=0; i<m; i++)
{
scanf("%d%d%d",&l,&r,&val);
update(1,l,r,val);
}
printf("Case %d: The total value of the hook is %d.\n",q,T[1].sum);
}
return 0;
}