首页 > 代码库 > hdu 4027 Can you answer these queries?(线段树)
hdu 4027 Can you answer these queries?(线段树)
题目大意:hdu 4027 Can you answer these queries?
题目大意:给定一个长度为N的序列,Q次操作,0 l r:将区间l r之间的数开根;1 l r:查询l r之间数的和。
解题思路:这题看上去是一道线段树,其实它就是一道线段树,只不过不用想的太复杂,因为开根的趋近1的速度非常快,所以每个节点只要标记区间内元素是否相同即可。复杂度妥妥的。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100000;
int N, Q;
ll P[maxn + 5];
#define lson(x) ((x)<<1)
#define rson(x) (((x)<<1)|1)
int lc[maxn << 2], rc[maxn << 2];
ll s[maxn << 2], v[maxn << 2];
inline void maintain(int u, ll d) {
v[u] = d;
s[u] = d * (rc[u] - lc[u] + 1);
}
inline void pushup(int u) {
s[u] = s[lson(u)] + s[rson(u)];
v[u] = (v[lson(u)] == v[rson(u)] ? v[lson(u)] : 0);
}
inline void pushdown(int u) {
if (v[u]) {
maintain(lson(u), v[u]);
maintain(rson(u), v[u]);
v[u] = 0;
}
}
void build (int u, int l, int r) {
lc[u] = l;
rc[u] = r;
if (l == r) {
v[u] = s[u] = P[l];
return;
}
int mid = (l + r) / 2;
build(lson(u), l, mid);
build(rson(u), mid + 1, r);
pushup(u);
}
void modify(int u, int l, int r) {
if (l <= lc[u] && rc[u] <= r && v[u]) {
maintain(u, (ll)sqrt((double)v[u]));
return;
}
pushdown(u);
int mid = (lc[u] + rc[u]) / 2;
if (l <= mid)
modify(lson(u), l, r);
if (r > mid)
modify(rson(u), l, r);
pushup(u);
}
ll query(int u, int l, int r) {
if (l <= lc[u] && rc[u] <= r)
return s[u];
pushdown(u);
ll ret = 0;
int mid = (lc[u] + rc[u]) / 2;
if (l <= mid)
ret += query(lson(u), l, r);
if (r > mid)
ret += query(rson(u), l, r);
pushup(u);
return ret;
}
int main () {
int kcas = 1;
while (scanf("%d", &N) == 1) {
for (int i = 1; i <= N; i++)
scanf("%I64d", &P[i]);
build(1, 1, N);
printf("Case #%d:\n", kcas++);
int t, l, r;
scanf("%d", &Q);
while (Q--) {
scanf("%d%d%d", &t, &l, &r);
if (l > r)
swap(l, r);
if (t)
printf("%I64d\n", query(1, l, r));
else
modify(1, l, r);
}
printf("\n");
}
return 0;
}
hdu 4027 Can you answer these queries?(线段树)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。