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.
Sample Input Sample Output
Case : The total value of the hook is .
题意:
输入T,表示T组样例,输入n,表示有n个节点,最初所有点的值为1,然后给定X、Y、Z,将从X到Y改为权值为Z,计算权值和。
思路:
线段树区间更新的模板。
代码:
#include <cstdio>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
struct node
{
int l,r;
int w;
}tree[];
void build(int l,int r,int n)
{
tree[n].l = l;
tree[n].r = r;
tree[n].w = ;
if(l == r)
return ;
int temp = (l+r)/;
build(l,temp,*n);
build(temp+,r,*n+);
}
void update(int l,int r,int w,int n)
{
if(tree[n].l == l&&tree[n].r == r)
{
tree[n].w = w;
return;
}
if(tree[n].w!=-)//将值更改为-1,代表这个区间内的值都已经更改
{
tree[*n].w = tree[*n+].w = tree[n].w;
tree[n].w = -;
}
int temp=(tree[n].l+tree[n].r)/;
if(r <= temp)
update(l,r,w,*n);
else if(l>temp)
update(l,r,w,*n+);
else
{
update(l,temp,w,*n);
update(temp+,r,w,*n+);
}
}
int find(int n)//查找
{
if(tree[n].w != -)//如果节点不为-1,表示这个区间内的值都是tree[n].w
{
return (tree[n].r-tree[n].l+)*tree[n].w;
}
else//如果节点为-1,递归下去。
{
return find(*n)+find(*n+);
}
}
int main()
{
int T;
scanf("%d",&T);
for(int i=; i<=T; i++)
{
int n;
scanf("%d",&n);
build(,n,);
int p;
scanf("%d",&p);
while(p--)
{
int a,b,w;
scanf("%d%d%d",&a,&b,&w);
update(a,b,w,);
}
printf("Case %d: ",i);
printf("The total value of the hook is %d.\n",find());
}
}