题目其实是比较基础的线段树区间更新题。然后要注意的是,make树的时候,lazy tag要记得归0(因为个人习惯是在初始化的时候直接把lazy tag=0初始化,因此,如果有多组数据,只是这样做而不在make的时候进行初始化就会有错误。)
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = 1e5+10;
struct node
{
int l, r;
ll sum; ll tag;
node(){
this->tag = 0;
}
};
vector<node> tree(MAXN << 2);
ll query(int idx);
void update(int idx, int l, int r, ll v);
void pushDown(int idx);
void make(int idx, int l, int r);
void pushUp(int idx);
signed main(){
int T; int N; int Q;
int l, r;
ll v;
scanf("%d", &T);
for(int ca = 1; ca <= T; ca++){
scanf("%d", &N); scanf("%d", &Q);
make(1, 1, N);
for(int i = 0; i < Q; i++){
scanf("%d %d %lld", &l, &r, &v);
update(1, l, r, v);
}
ll ans = query(1);
printf("Case %d: The total value of the hook is %lld.\n",ca, ans);
}
return 0;
}
ll query(int idx){
return tree[idx].sum;
}
void update(int idx, int l, int r, ll v){
if(tree[idx].l >=l && tree[idx].r <= r){
tree[idx].sum = ll(tree[idx].r - tree[idx].l + 1)*v; tree[idx].tag = v;
return;
}
if(tree[idx].tag != 0) pushDown(idx);
int mid = (tree[idx].l + tree[idx].r) / 2;
if(l <=mid) update(idx << 1, l, r, v);
if(r > mid) update(idx << 1 |1, l, r, v);
pushUp(idx);
}
void pushDown(int idx){
int tag = tree[idx].tag; tree[idx].tag = 0;
tree[idx << 1].tag = tag;
tree[idx << 1].sum = ll(tree[idx <<1]. r - tree[idx<<1].l + 1)*tag;
tree[idx << 1|1].tag = tag;
tree[idx << 1|1].sum = ll(tree[idx <<1|1]. r - tree[idx<<1|1].l + 1)*tag;
return;
}
void make(int idx, int l, int r){
if(l == r) {tree[idx].l = l; tree[idx].r = r; tree[idx].tag = 0;tree[idx].sum = 1; return;}
int mid = (l + r) >> 1;
make(idx << 1, l, mid);
make(idx << 1 |1, mid+1, r);
tree[idx].l = l; tree[idx].r = r; tree[idx].tag = 0;
pushUp(idx);
}
void pushUp(int idx){
tree[idx].sum = tree[idx << 1].sum + tree[idx <<1 |1].sum;
return;
}