Copil Copac is given a list of n − 1 n-1 n−1 edges describing a tree of n n n vertices. He decides to draw it using the following algorithm:
- Step 0 0 0: Draws the first vertex (vertex 1 1 1). Go to step 1 1 1.
- Step 1 1 1: For every edge in the input, in order: if the edge connects an already drawn vertex u u u to an undrawn vertex v v v, he will draw the undrawn vertex v v v and the edge. After checking every edge, go to step 2 2 2.
- Step 2 2 2: If all the vertices are drawn, terminate the algorithm. Else, go to step 1 1 1.
The number of readings is defined as the number of times Copil Copac performs step 1 1 1.
Find the number of readings needed by Copil Copac to draw the tree.
Input
Each test contains multiple test cases. The first line of input contains a single integer t t t ( 1 ≤ t ≤ 1 0 4 1 \leq t \leq 10^4 1≤t≤104) — the number of test cases. The description of test cases follows.
The first line of each test case contains a single integer n n n ( 2 ≤ n ≤ 2 ⋅ 1 0 5 2 \le n \le 2 \cdot 10^5 2≤n≤2⋅105) — the number of vertices of the tree.
The following n − 1 n - 1 n−1 lines of each test case contain two integers u i u_i ui and v i v_i vi ( 1 ≤ u i , v i ≤ n 1 \le u_i, v_i \le n 1≤ui,vi≤n, u i ≠ v i u_i \neq v_i ui=vi) — indicating that ( u i , v i ) (u_i,v_i) (ui,vi) is the i i i-th edge in the list. It is guaranteed that the given edges form a tree.
It is guaranteed that the sum of n n n over all test cases does not exceed 2 ⋅ 1 0 5 2 \cdot 10^5 2⋅105.
Output
For each test case, output the number of readings Copil Copac needs to draw the tree.
Example
input
2
6
4 5
1 3
1 2
3 4
1 6
7
5 6
2 4
2 7
1 3
1 2
4 5
output
2
3
Note
In the first test case:
After the first reading, the tree will look like this:
After the second reading:
Therefore, Copil Copac needs 2 2 2 readings to draw the tree.
解题思路
给所有的边从上到下依次进行编号(1~n),然后从顶点1开始建树,每次只能添加编号比当前编号大的边,如果出现编号小的边就相当于从新做了一次操作,操作数就加一
代码实现
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
vector<pair<int,int>>s[N];
int n,ans;
void dfs(int v,int oj,int w=0){
ans=max(ans,w);
for(pair<int,int> i: s[v]){
if(i.second!=oj)
dfs(i.first,i.second,w+(i.second<oj)); //如果下一条边的编号小于当前边,操作数+1
}
}
void solve(){
cin>>n;
for(int i=1;i<=n;i++)s[i].clear();
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
s[a].push_back({b,i}); //存边和边的编号
s[b].push_back({a,i});
}
ans=0;
dfs(1,0);
ans++;
cout<<ans<<endl;
}
int main(){
int t;
cin>>t;
while(t--)
solve();
return 0;
}