您的位置:首页 > 产品设计 > UI/UE

Can you answer these queries? HDU - 4027(线段树)

2017-08-14 11:07 411 查看
链接:http://acm.hdu.edu.cn/showproblem.php?pid=4027

题意:给你一段区间n, 以及[1, n]中的每一个数,两个操作:

0, x, y 对于区间[x, y]对每一个数字去开方(向下取整)

1, x, y查询区间[x, y]的和

解题思路:

考虑到对于一个long long 类型的整数开方不会用多少次就会变成1, 而如果变成1以后还要去开方就会浪费许多的时间,于是用一个标记标记当前的节点是否全是1, 或者1和0, 如果是则不再更新

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <math.h>

#define LL long long
#define lson ins<<1
#define rson ins<<1|1
#define mid (l+r)/2

const int Max = 101000;
using namespace std;
struct node {
int l, r, lazy;
LL sum;
} tree[Max << 2];
LL data[Max << 2];

inline void push_up(int ins) {
tree[ins].sum = tree[lson].sum + tree[rson].sum;
if (tree[lson].lazy && tree[rson].lazy)tree[ins].lazy = 1;
}//向上传递标记

inline void build(int l, int r, int ins) {
tree[ins].l = l, tree[ins].r = r, tree[ins].sum = tree[ins].lazy = 0;
if (l == r) {
tree[ins].sum = data[l];
if (data[l] <= 1)tree[ins].lazy = 1;
} else {
build(l, mid, lson);
build(mid + 1, r, rson);
push_up(ins);
}
}

inline void updata(int ql, int qr, int ins) {
int l = tree[ins].l, r = tree[ins].r;
if (l == r) {
tree[ins].sum = (LL) sqrt(tree[ins].sum);
if (tree[ins].sum <= 1)tree[ins].lazy = 1;
} else {
if (ql <= mid && !tree[lson].lazy)updata(ql, qr, lson);//如果全是1或0不再更新
if (qr > mid && !tree[rson].lazy)updata(ql, qr, rson);
push_up(ins);
}
}

inline LL query(int ql, int qr, int ins) {
int l = tree[ins].l, r = tree[ins].r;
if (ql <= l && qr >= r) {
return tree[ins].sum;
} else {
LL res = 0;
if (ql <= mid)res += query(ql, qr, lson);
if (qr > mid)res += query(ql, qr, rson);
return res;
}
}

int main() {
int n, cases = 1;
while (~scanf("%d", &n)) {
for (int a = 1; a <= n; a++) {
scanf("%lld", &data[a]);
}
build(1, n, 1);
int m;
printf("Case #%d:\n", cases++);
scanf("%d", &m);
for (int a = 0; a < m; a++) {
int i, j, k;
scanf("%d%d%d", &i, &j, &k);
if (j > k)swap(j, k);
if (i == 0) {
updata(j, k, 1);
} else if (i == 1) {
LL ans = query(j, k, 1);
printf("%lld\n", ans);
}
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: