您的位置:首页 > 其它

HDU 1698 Just a Hook (线段树 成段更新)

2015-08-16 11:04 555 查看
题目大意:

就是现在一串钩子初始每个部分价值为1, 每次操作修改其中连续的一整段的价值, 问经过Q次操作之后整串钩子的总价值

钩子长度N <= 100000, 操作次数Q <= 100000

大致思路:

就是用懒惰标记来进行延迟更新, 使得每次更新的复杂度保持在O(logn)的级别, 注意一下懒惰标记的下推即可

代码如下:

Result  :  Accepted     Memory  :  1684 KB     Time  :  998 ms

/*
* Author: Gatevin
* Created Time: 2015/8/16 10:43:12
* File Name: Sakura_Chiyo.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

#define maxn 100010

struct Segment_Tree
{
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
int val[maxn << 2];
int flag[maxn << 2];//懒惰标记
void pushUp(int rt)
{
flag[rt] = 0;
val[rt] = val[rt << 1] + val[rt << 1 | 1];
return;
}
void pushDown(int l, int r, int mid, int rt)
{
if(flag[rt])
{
flag[rt << 1] = flag[rt << 1 | 1] = flag[rt];
val[rt << 1] = (mid - l + 1)*flag[rt];
val[rt << 1 | 1] = (r - mid)*flag[rt];
flag[rt] = 0;
}
return;
}
void build(int l, int r, int rt)
{
if(l == r)
{
val[rt] = 1;
flag[rt] = 0;
return;
}
int mid = (l + r) >> 1;
build(lson);
build(rson);
pushUp(rt);
return;
}
void update(int l, int r, int rt, int L, int R, int value)
{
if(l >= L && r <= R)
{
val[rt] = (r - l + 1)*value;
flag[rt] = value;
return;
}
int mid = (l + r) >> 1;
pushDown(l, r, mid, rt);//向下推懒惰标记
if(mid >= L) update(lson, L, R, value);
if(mid + 1 <= R) update(rson, L, R, value);
pushUp(rt);
}
int query(int l, int r, int rt, int L, int R)
{
if(l >= L && r <= R)
return val[rt];
int mid = (l + r) >> 1;
pushDown(l, r, mid, rt);
int ret = 0;
if(mid >= L) ret += query(lson, L, R);
if(mid + 1 <= R) ret += query(rson, L, R);
return ret;
}
};

Segment_Tree ST;

int main()
{
int n, T;
scanf("%d", &T);
for(int cas = 1; cas <= T; cas++)
{
scanf("%d", &n);
ST.build(1, n, 1);
int Q;
scanf("%d", &Q);
while(Q--)
{
int l, r, v;
scanf("%d %d %d", &l, &r, &v);
ST.update(1, n, 1, l, r, v);
}
printf("Case %d: The total value of the hook is %d.\n", cas, ST.query(1, n, 1, 1, n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息