D - Just a Hook
阿新 • • 發佈:2018-11-15
題目連結:https://cn.vjudge.net/contest/269834#problem/D
題目大意:剛開始給你n個點,每個點的價值是1,然後會區間更新價值,詢問最後總的價值是多少。
題解:lazy演算法。
程式碼:
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; struct node { int l,r,num; int lazy; } s[2000000]; int h[2000000]; void creat(int t,int l,int r)//建樹 { int mid=(l+r)>>1; if(l==r) { s[t].l=l; s[t].r=r; s[t].lazy=1; return ; } s[t].l=l; s[t].r=r; s[t].lazy=1; creat(t*2,l,mid); creat(t*2+1,mid+1,r); } void addre(int t,int l,int r,int e)//區間更新 { int mid=(s[t].l+s[t].r)>>1; if(s[t].l==l&&s[t].r==r) { s[t].lazy=e; return ; } if(s[t].lazy!=0) { s[t*2+1].lazy=s[t].lazy; s[t*2].lazy=s[t].lazy; s[t].lazy=0; } if(mid>=r) { addre(t*2,l,r,e); } else if(mid<l) { addre(t*2+1,l,r,e); } else { addre(t*2,l,mid,e); addre(t*2+1,mid+1,r,e); } } int query(int t)//查詢總價值 { if(s[t].lazy==0) { return query(t*2)+query(t*2+1); } else return (s[t].r-s[t].l+1)*s[t].lazy; } int main() { int T; int a,b,c,d,e,mm=0; scanf("%d",&T); while(T--) { ++mm; scanf("%d %d",&a,&b); creat(1,1,a); for(int i=1; i<=b; i++) { scanf("%d %d %d",&c,&d,&e); addre(1,c,d,e); } printf("Case %d: The total value of the hook is %d.\n",mm,query(1)); } return 0; }