题目链接:HDU-1698
题目描述:
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.
思路
区间修改,询问区间和。 典型的线段树板子题;
易错
1.需要用到lazy标记;
代码
#include <bits/stdc++.h>
using namespace std;
#define long long long
#define MAX 100010
struct Node{
long l, r, sum, lazy;
void updata(long val)
{
sum = (r - l + 1) * val;
lazy = val;
}
}tree[MAX * 4];
void push_up(int k)
{
tree[k].sum = tree[k<<1].sum + tree[k<<1|1].sum;
}
void push_down(int k)
{
long lazyval = tree[k].lazy;
if(lazyval)
{
tree[k<<1].updata(lazyval);
tree[k<<1|1].updata(lazyval);
tree[k].lazy = 0;
}
}
void build(int k, int l, int r)
{
tree[k].l = l, tree[k].r = r;
tree[k].sum = tree[k].lazy = 0;
if(l == r)
{
tree[k].sum = 1;
}
else
{
int mid = (l + r) >> 1;
build(k<<1, l, mid);
build(k<<1|1, mid+1, r);
push_up(k);
}
}
void updata(int k, int l, int r, int val)
{
int L = tree[k].l, R = tree[k].r;
if(l <= L && R <= r)
{
tree[k].updata(val);
}
else
{
push_down(k);
int mid = (L + R) >> 1;
if(l <= mid)
updata(k<<1, l, r, val);
if(mid < r)
updata(k<<1|1, l, r, val);
push_up(k);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
for(int i = 1; i<=t; i++)
{
int n, m;
cin >> n >> m;
build(1, 1, n);
for(int j = 1; j<=m; j++)
{
int x, y, val;
cin >> x >> y >> val;
updata(1, x, y, val);
}
cout << "Case " << i << ": The total value of the hook is " << tree[1].sum << "." << endl;
}
return 0;
}