LightOJ 1080 Binary Simulation

本文介绍了一道典型的线段树模板题,通过实例演示了如何使用线段树进行区间更新和查询操作。代码中详细展示了线段树的构建、更新及查询过程。

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

线段树模板题,开始用scanf("%c")一直错。。。

#include <iostream>
#include <cstdio>
#include <cstring>

const int MAX = 1e5 + 5;
char arr[MAX];
int res[3 * MAX];

void update(int idx, int st, int ed, int q_st, int q_ed)
{
	if (st == q_st && q_ed == ed)
	{
		res[idx]++;
		return;
	}
	int m = (st + ed) >> 1;
	int l = idx << 1, r = l | 1;
	if (q_ed <= m)
	{
		update(l, st, m, q_st, q_ed);
	}
	else if (q_st > m)
	{
		update(r,m + 1, ed, q_st, q_ed);
	}
	else
	{
		update(l, st, m, q_st, m);
		update(r, m + 1, ed, m + 1, q_ed);
	}
}

int query(int idx, int st, int ed, int pos)
{
	if (st == pos && ed == pos)
	{
		return res[idx];
	}
	int m = (st + ed) >> 1;
	int l = idx << 1, r = l | 1;
	if (pos <= m)
	{
		return query(l, st, m, pos) + res[idx];
	}
	else
	{
		return query(r, m + 1, ed, pos) + res[idx];
	}
}

int main()
{
	int t, cas = 0;
	scanf("%d", &t);
	while (t--)
	{
		memset(res, 0, sizeof(res));	
		int q;
		scanf("%s", arr + 1);
		int lenth = strlen(arr + 1);
		scanf("%d", &q);

		char type[2];
		int q_st, q_ed, pos;
		printf("Case %d:\n", ++cas);
		for (int i = 1; arr[i]; ++i)
		{
			if (arr[i] == '1')
				update(1, 1, lenth, i, i);
		}
		for (int i = 0; i != q; ++i)
		{
			scanf("%s", type);
			if (type[0] == 'I')
			{
				scanf("%d%d", &q_st, &q_ed);
				update(1, 1, lenth, q_st, q_ed);
			}
			else if (type[0] == 'Q')
			{
				scanf("%d", &pos);
				printf("%d\n",query(1, 1, lenth, pos) & 1);
			}
		}
	}
	return  0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值