Given a tree with vertices, which are numbered by integers from 1 to , 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 (about 5), indicating the number of test cases. For each test case:
The first line contains two integers and (), indicating the number of vertices and the number of queries.
The following lines each contains two integers and (), indicating an edge connecting vertex and in the tree.
The following lines each contains two integers and (), 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个节点,q个询问,询问[l,r]之间联通块的个数。
思路:先求1-n点的路径数用树状数组存着,然后保存q个询问,按照左边的点从小到大排序,那么要求的就是r-l+1-qh(r),我们需要不断更新点对应的值,因为前面的点已经没用了。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N=222222;
struct node
{
int l,r,n;
}q[N];
int n,m;
vector<int>g[N];
int c[N],ans[N];
bool cmp(node a,node b)
{
return a.l<b.l;
}
int lowbit(int x)
{
return x&(-x);
}
void update(int x,int y)
{
while(x<=n)
{
c[x]+=y;
x+=lowbit(x);
}
}
int qh(int x)
{
int sum=0;
while(x)
{
sum+=c[x];
x-=lowbit(x);
}return sum;
}
int main()
{
int T;
cin>>T;
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)g[i].clear();
for(int i=0;i<n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
int u1=max(u,v);
int v1=min(u,v);
g[v1].push_back(u1);
update(u1,1);
}
for(int i=0;i<m;i++)
{
scanf("%d%d",&q[i].l,&q[i].r);
q[i].n=i;
}
sort(q,q+m,cmp);
int pos=0;
for(int i=1;i<=n;i++)
{
while(pos<m&&q[pos].l==i)
{
ans[q[pos].n]=q[pos].r-q[pos].l+1-qh(q[pos].r);
pos++;
}
for(int j=0;j<g[i].size();j++)
{
update(g[i][j],-1);
}
}
for(int i=0;i<m;i++)
{
printf("%d\n",ans[i]);
}
}
return 0;
}