CF264E Roadside Trees <线段树>
Problem
Roadside Trees
Description
Squirrel Liss loves nuts. Liss asks you to plant some nut trees.
There are positions (numbered 1 to from west to east) to plant a tree along a street. Trees grow one meter per month. At the beginning of each month you should process one query. The query is one of the following types:
- Plant a tree of height at position .
- Cut down the existent (not cut) tree from the west (where is 1-indexed). When we cut the tree it drops down and takes all the available place at the position where it has stood. So no tree can be planted at this position anymore.
After processing each query, you should print the length of the longest increasing subsequence. A subset of existent trees is called an increasing subsequence if the height of the trees in the set is strictly increasing from west to east (for example, the westmost tree in the set must be the shortest in the set). The length of the increasing subsequence is the number of trees in it.
Note that Liss don’t like the trees with the same heights, so it is guaranteed that at any time no two trees have the exactly same heights.
Input
The first line contains two integers: and – the number of positions and the number of queries.
Next lines contains the information of queries by following formats:
- If the query is type 1, the line contains three integers: 1, , and , where is the position of the new tree and is the initial height of the new tree.
- If the query is type 2, the line contains two integers: 2 and , where the is the index of the tree we want to cut.
The input is guaranteed to be correct, i.e., - For type 1 queries, will be pairwise distinct.
- For type 2 queries, will be less than or equal to the current number of trees.
- At any time no two trees have the exactly same heights.
In each line integers are separated by single spaces.
Output
Print integers – the length of the longest increasing subsequence after each query. Separate the numbers by whitespaces.
Example
Input
1 | 4 6 |
Output
1 | 1 |
标签:线段树
Translation
有一条有 个位置的路,现有 个操作,分为两种:
- 在第 个位置种下一棵高度为 的树
- 砍掉从左向右第 棵树
每个单位时间内,树会长高米。
每次操作后,输出当前最长上升子序列的长度。
数据保证任意时刻没有两棵树高度相同。
Solution
由于比较大,显然不能用二维树状数组/线段树维护。
考虑最长上升子序列如何。从后往前,每次找到后面的数值比当前大的位置,选出其中值最大的加,作为当前位置的值。找后面符合条件的最大值可以用线段树维护。如果将位置和数值作为值放到坐标系上,发现如果将值对换后,问题是完全相同的。于是可以得到另一种方法:从数值最大的向数值最小的,每次找到比其大的数值中对应位置在其后面的数对应的值的最大值,将最大值加作为当前数的值。同样地,这种方法也可以用线段树维护。
观察题目中的特殊条件,发现均不大于。如果插入一棵高度为的树,则需要将所有高度小于的树的值重新计算;如果砍掉第棵树,则需要将第棵树的值重新计算。每次重新计算的位置均不大于个。
考虑维护两棵线段树,分别对应前面的两种方式(第一棵按从大到小算,第二棵按从大到小算)。种树时,找出所有高度小于的位置,将第一棵线段树中对应位置的值清零,按高度从大到小排序,然后依次计算值,由于到每个位置时,比它高的树都已经被过了,所以可以保证正确性。砍树时,找出第棵树,将第二棵线段树中对应高度的值清零,从后向前依次计算值,正确性同样可以保证。注意修改值时在两棵线段树上都需要修改。
为了快速找到前棵树,可以维护一个堆,存储当前有树的位置,每次弹出前小即可。
总时间复杂度。
附上官方题解
Code
1 |
|