Consider a un-rooted tree T which is not the biological significance of tree or plant, but a tree as an undirected graph in graph theory with n nodes, labelled from 1 to n. If you cannot understand the concept of a tree here, please omit this problem.
Now we decide to colour its nodes with k distinct colours, labelled from 1 to k. Then for each colour i = 1, 2, · · · , k, define Ei as the minimum subset of edges connecting all nodes coloured by i. If there is no node of the tree coloured by a specified colour i, Ei will be empty.
Try to decide a colour scheme to maximize the size of E1 ∩ E2 · · · ∩ Ek, and output its size.
Now we decide to colour its nodes with k distinct colours, labelled from 1 to k. Then for each colour i = 1, 2, · · · , k, define Ei as the minimum subset of edges connecting all nodes coloured by i. If there is no node of the tree coloured by a specified colour i, Ei will be empty.
Try to decide a colour scheme to maximize the size of E1 ∩ E2 · · · ∩ Ek, and output its size.
InputThe first line of input contains an integer T (1 ≤ T ≤ 1000), indicating the total number of test cases.
For each case, the first line contains two positive integers n which is the size of the tree and k (k ≤ 500) which is the number of colours. Each of the following n - 1 lines contains two integers x and y describing an edge between them. We are sure that the given graph is a tree.
The summation of n in input is smaller than or equal to 200000.
OutputFor each test case, output the maximum size of E1 ∩ E1 ... ∩ Ek.Sample Input
3 4 2 1 2 2 3 3 4 4 2 1 2 1 3 1 4 6 3 1 2 2 3 3 4 3 5 6 2
Sample Output
1 0 1
题解:考虑某条边,则只要两边的2个顶点都大于等于k,则连边时一定会经过这条边,ans++;
参看代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define clr(a,b,n) memset((a),(b),sizeof(int)*n) 4 typedef long long ll; 5 const int maxn = 2e5+10; 6 int n,k,ans,num[maxn]; 7 vector<int> vec[maxn]; 8 9 void dfs(int u,int fa) 10 { 11 num[u]=1; 12 for(int i=0;i<vec[u].size();i++) 13 { 14 int v=vec[u][i]; 15 if(v==fa) continue; 16 dfs(v,u); 17 num[u]+=num[v]; 18 if(num[v]>=k&&n-num[v]>=k) ans++; 19 } 20 } 21 22 int main() 23 { 24 int T,u,v; 25 scanf("%d",&T); 26 while(T--) 27 { 28 scanf("%d%d",&n,&k); 29 clr(num,0,n+1); ans=0; 30 for(int i=1;i<=n;i++) vec[i].clear(); 31 for(int i=1;i<n;i++) 32 { 33 scanf("%d%d",&u,&v); 34 vec[u].push_back(v); 35 vec[v].push_back(u); 36 } 37 dfs(1,-1); 38 //for(int i=1;i<=n;++i) cout<<num[i]<<endl; 39 printf("%d ",ans); 40 } 41 return 0; 42 }