hdu1698 Just a Hook--区间更新

原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1698


一:题意
一根钩子由n个sticks组成,分别标记为1到n,现在给定m组操作,x,y,z表示把x到y位置的sticks换成z类型的,一共三种类型,金银铜,价值分别等价于3,2,1,钩子初始状态都是铜级别的,现在要你求在经过m组操作后整个钩子的总价值价值。


二:分析
线段树区间更新,和单点更新不一样,新增设置节点的值为-1表示在该节点下的级别是杂乱的,混有三种类型的至少两种,如果该节点值就是1或者2或者3,那么该节点下的所有节点值都是1或者2或者3。


三:AC代码
#define _CRT_SECURE_NO_DEPRECATE 

#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;

int a[100000 * 4];
int t;
int n, m;
int x, y, z;

void build(int l, int r, int root)
{
	a[root] = 1;
	if (l == r)
		return;

	build(l, (l + r) / 2, root * 2);
	build((l + r) / 2 + 1, r, root * 2 + 1);
}

void update(int l, int r, int root, int x, int y, int z)
{
	if (a[root] == z)//该节点孩子都是z类型的,不用更新了
		return;

	if (l == x&&r == y)//找到区间
	{
		a[root] = z;
		return;
	}

	if (a[root] != -1)//说明该节点的孩子的类型都是一样的
	{
		a[root * 2] = a[root * 2 + 1] = a[root];//实时更新孩子节点
		a[root] = -1;
	}

	int mid = (l + r) / 2;
	if (x > mid)
		update(mid + 1, r, root * 2 + 1, x, y, z);
	else if (y <= mid)
		update(l, mid, root * 2, x, y, z);
	else
	{
		update(l, mid, root * 2, x, mid, z);
		update(mid + 1, r, root * 2 + 1, mid + 1, y, z);
	}
}

int find(int l, int r, int root)
{
	if (a[root] != -1)
		return (r - l + 1)*a[root];
	else
		return find(l, (l + r) / 2, root * 2) + find((l + r) / 2 + 1, r, root * 2 + 1);
}

int main()
{
	int cas = 1;
	scanf("%d", &t);

	for (; cas <= t; cas++)
	{
		scanf("%d%d", &n, &m);

		build(1, n, 1);

		for (int i = 0; i < m; i++)
		{
			scanf("%d%d%d", &x, &y, &z);
			update(1, n, 1, x, y, z);
		}

		printf("Case %d: The total value of the hook is %d.\n", cas, find(1, n, 1));
	}

	return 0;
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值