【DFS+思维】HDU - 6228 L - Tree

L - Tree  HDU - 6228

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.

Input

The 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. 

Output

For 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

DFS出每个节点的子节点数(包括自己本身)

那么每条边要是左边>=k,右边>=k

那么ans++

因为不同颜色左右各选一个点,全部连起来之后,这条边就是公共边

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;
int head[maxn],to[maxn],nxt[maxn],num[maxn];
int n,k,e,ans;

void add(int u,int v)
{
    e++;
    to[e]=v;
    nxt[e]=head[u];
    head[u]=e;
}

void dfs(int u,int fa)
{
    num[u]=1;
    for(int i=head[u];i!=-1;i=nxt[i])
    {
        int v=to[i];
        if(v==fa) continue;
        dfs(v,u);
        num[u]+=num[v];
    }
    if(num[u]>=k&&n-num[u]>=k) ans++;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        e=0;
        memset(head,-1,sizeof(head));
        memset(num,0,sizeof(num));
        scanf("%d%d",&n,&k);
        for(int i=1;i<n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add(u,v),add(v,u);
        }
        ans=0;
        dfs(1,0);
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/82888804
今日推荐