yet-another-tree-query-problem
Yet Another Tree Query Problem
Time Limit: 3 Seconds Memory Limit: 65536 KB
Given a tree with vertices, which are numbered by integers from 1 to n, there are queries.
Each query can be described with two integers and . A vertex is good, if and only if ; An edge is good, if and only if both and are good. Please print the number of connected components consist of all the good vertices and the good edges.
Input
There are multiple test cases. The first line of the input is an integer T (about 5), indicating the number of test cases. For each test case:
The first line contains two integers n and q (), indicating the number of vertices and the number of queries.
The following lines each contains two integers u and v(), indicating an edge connecting vertex and in the tree.
The following q lines each contains two integers l and r (), indicating a query.
It’s guaranteed that the given graph is a tree.
Output
For each query output one line containing one integer, indicating the answer.
Sample Input
2
4 6
1 4
4 3
3 2
1 2
2 3
3 4
1 3
2 4
1 4
3 2
1 3
2 3
1 2
2 3
Sample Output
2
1
1
2
1
1
2
1
Hint
For the six queries in case 1, the connected components are listed as follows:
[1], [2]
[2, 3]
[3, 4]
[1], [2, 3]
[2, 3, 4]
[1, 2, 3, 4]
For the two queries in case 2, the connected components are as follows:
[1], [2]
[2, 3]
题意:
给出一个有n个结点的树,结点为.输入n-1行表示所有边u,v。 每个询问都会给出l,r。
good point为数字在的点。good edge为两个good point连起来的边。good component为几个good point 或 edge 连起来的部分。对于每次询问l,r,求出有多少个good component。
解法
good component的数量其实就是good point-good edge .
good point=r-l+1.
问题就在good edge上,good edge 的条件是两个端点都在,普通做法就是.
如何求出这个数量呢?
在图中,以u,v为坐标轴,那么每个边都是图上的一个点,每次查询也是一个关键点,所需要的答案就是黄色矩形中的点的数量
我们知道一维线段树是一个线段每次对半分开,作为其两个儿子,那么二维线段树就是矩形的中间分开分成四份作为其四个儿子。具体操作和一维线段树一样。
以此类推三维线段树是立方体从中心分成8份,四维线段树每次分成16份。。。。。
1 |
|
总结:
给出很多区间如图,如何快速求出内的区间(左端点大于且右端点小于)。对于图中的情况答案应该为2。
这类问题就可以用二维线段树将每个区间都转变为二维平面上的一个点,
所求的答案就是
用线段树维护区间和即可