UVa12532 - Interval Product(Fenwick树)

本文介绍了一个基于Fenwick树(二叉索引树)实现的区间查询与更新操作的数据结构应用案例。该程序能够高效处理数组中元素的查询与修改,并支持查询指定区间内的元素个数。特别地,针对负数和零值进行了专门处理。
#include <cstdio>
#include <vector>

using namespace std;

const int N = 100010;

struct Fenwick
{
private:
	vector<int> fw;
	
public:
	int lowbit(int n)
	{
		return n & (-n);
	}
	
	void init(int n)
	{
		fw.assign(n + 1, 0);
	}
	
	int sum(int n)
	{
		int s = 0;
		while (n > 0) {
			s += fw[n];
			n -= lowbit(n);
		}
		
		return s;
	}
	
	int sum(int a, int b)
	{
		return sum(b) - (a == 1 ? 0 : sum(a - 1));
	}
	
	void adjust(int k, int v)
	{
		while (k < (int)fw.size()) {
			fw[k] += v;
			k += lowbit(k);
		}
	}
};

struct solution
{
private:
	int x[N];
	int n, k;
	Fenwick neg, zero;
	
public:
	bool input()
	{
		if (scanf("%d%d", &n, &k) != 2) return false;
		
		neg.init(n);
		zero.init(n);
		
		for (int i = 1; i <= n; i++) {
			scanf("%d", &x[i]);
			if (x[i] < 0) neg.adjust(i, 1);
			else if (x[i] == 0) zero.adjust(i, 1);
		}
		
		return true;
	}
	
	void solve()
	{
		for (int i = 0; i < k; i++) {
			char ch;
			scanf("%c", &ch);

			while (ch != 'P' && ch != 'C') {
				scanf("%c",  &ch);
			}
			
			int a, b;
			scanf("%d%d", &a, &b);
			
			if (ch == 'P') {
				if (zero.sum(a, b)) {
					printf("0");
				} else if (neg.sum(a, b) & 1) {
					printf("-");
				} else {
					printf("+");
				}
			} else {
				if (x[a] < 0 && b >= 0) {
					neg.adjust(a, 1);
				} else if (x[a] >= 0 && b < 0) {
					neg.adjust(a, 1);
				}
				
				if (x[a] != 0 && b == 0) {
					zero.adjust(a, 1);
				} else if (x[a] == 0 && b != 0) {
					zero.adjust(a, -1);
				}
				
				x[a] = b;
			}
		}
		
		printf("\n");
	}
};

int main()
{
#ifndef ONLINE_JUDGE
	freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif

	solution solver;
	while (solver.input()) {
		solver.solve();
	}
	 
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值