[Usaco2011 Dec]Grass Planting

本文介绍了一道关于树剖和线段树的应用题目,主要内容包括如何在树上进行区间修改和查询操作,特别是在面对复杂的重链跳跃时如何正确地使用懒标记(lazy tag)。文章还提供了一个具体的例子来说明实现细节。

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

Description

Farmer John has N barren pastures connected by N-1 bidirectional roads, such that there is exactly o
ne path between any two pastures. Bessie, a cow who loves her grazing time, often complains about ho
w there is no grass on the roads between pastures. Farmer John loves Bessie very much, and today he 
is finally going to plant grass on the roads. He will do so using a procedure consisting of M steps 
.
At each step one of two things will happen:
- FJ will choose two pastures, and plant a patch of grass along each road in between the two pastures, or,
- Bessie will ask about how many patches of grass on a particular road, and Farmer John must answer her question.
Farmer John is a very poor counter -- help him answer Bessie's questions!
大致题意: 维护一棵树,支持两种操作:
P x y x到y路径上的每条边的值+1;
Q x y 询问x到y路径上所有边的值的和。

Input

Line 1: Two space-separated integers N and M.
Lines 2..N: Two space-separated integers describing the endpoints of a road.
Lines N+1..N+M: Line i+1 describes step i. The first character of the line is either P or Q, which d
escribes whether or not FJ is planting grass or simply querying. This is followed by two space-separ
ated integers A_i and B_i (1 ≤A_i, B_i ≤N) which describe FJ's action or query.
第一行两个正整数,N,M表示点数和操作数;
接下来N-1行每行两个数表示一条边;
接下来M行表示M个操作,每行形如P x y或Q x y。
2≤N≤100,000,1≤M≤100,000。

Output

Lines 1..???: Each line has the answer to a query, appearing in the same order as the queries appear in the input.
M行,对应相应询问的答案。

Sample Input

4 6
1 4
2 4
3 4
P 2 3
P 1 3
Q 3 4
P 1 4
Q 2 4
Q 1 4

Sample Output

2
1
2

来写此题的一定都是学过树剖的了吧。

这道题用到了线段树的区间修改,难道真的只要在单点修改的情况下在线段树中使用lazy标记来进行区间修改就行了么

答案是否定的!!

你或许能过样例,但是肯定是红色的wa

我们知道树剖要不断的去跳重链,如果你要修改的区间不在一条重链上,那就会出错哦(样例很坑哦)

所以需要在加lazy标记的同时再不断地跳重链

代码:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值