BZOJ 3221 花神游历各国 (线段树)

本文介绍了解决BZOJ3221算法题目的方法,主要涉及数的开平方操作和线段树的应用。通过详细解释算法思路,提供了解题的步骤和关键点,帮助读者理解和解决类似问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:BZOJ 3221

最多进行5次操作,数将变为1,之后就不会改变。可以记录一个值col表示数是否需要开平方的操作。


#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
using namespace std;
#define LL long long

const int maxn = 100000 + 10;

int N, M;

int a[maxn];

struct node{
	int l, r, col;
	LL sum;
}t[maxn * 4];

inline int read(){
	int x = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9'){if(ch == '-')f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0'; ch = getchar();}
	return x * f;
}

void input(){
	N = read();
	for(int i = 1; i <= N; ++i){
		a[i] = read();
	}
}

void pushup(int x){
	if(t[x << 1].col || t[x << 1 | 1].col)t[x].col = 1;
	else t[x].col = 0;
	t[x].sum = t[x << 1].sum + t[x << 1 | 1].sum;
}

void built(int x, int l, int r){
	t[x].l = l; t[x].r = r;
	if(l == r){
		t[x].sum = (LL)a[l];
		if(t[x].sum <= 1)t[x].col = 0;
		else t[x].col = 1;
		return ;
	}
	int mid = (l + r) >> 1;
	built(x << 1, l, mid); built(x << 1 | 1, mid + 1, r);
	pushup(x);
}

LL ask(int x, int l, int r){
	if(t[x].l >= l && t[x].r <= r){
		return t[x].sum;
	}
	int mid = (t[x].l + t[x].r) >> 1;
	LL tot = 0;
	if(l <= mid)tot += ask(x << 1, l, r);
	if(r >  mid)tot += ask(x << 1 | 1, l, r);
	return tot;
}

void modify(int x, int l, int r){
	if(!t[x].col)return ;
	
	if(t[x].l >= l && t[x].r <= r && t[x].l == t[x].r){
		t[x].sum = (LL)sqrt(t[x].sum);
		if(t[x].sum <= 1)t[x].col = 0;
		else t[x].col = 1;
		return ;
	}
	int mid = (t[x].l + t[x].r) >> 1;
	if(l <= mid)modify(x << 1, l, r);
	if(r >  mid)modify(x << 1 | 1, l, r);
	pushup(x);
}

void solve(){
	built(1, 1, N);
	
	M = read();
	for(int i = 1; i <= M; ++i){
		int op = read(), L = read(), R = read();
		if(op == 1){
			printf("%lld\n", ask(1, L, R));
		}
		else{
			modify(1, L, R);
		}
	}
}

int main(){
	input();
	solve();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值