Tree(HDU 6228)

来源:互联网 发布:免费数据分析软件 编辑:程序博客网 时间:2024/06/04 23:31

Tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 538    Accepted Submission(s): 342



Problem Description
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
34 21 22 33 44 21 21 31 46 31 22 33 43 56 2
 

Sample Output
101
 
//题意:给定一棵树,用K种颜色给这棵树染色,把一种颜色的所有点连起来,经过的所有边为一个集合Ei。每种颜色都有一个E集合,求这些集合求交集后的集合大小(即集合里元素个数)。

//思路

1. 因为如果k中颜色里有一种颜色没用,那么这种颜色对应的集合E为空集,即最后的答案为0,显然是最差的情况,所以,这K种颜色都要用。

2. 一条边可以把一棵树分成两个部分(因为树没有环),如果这两部分里的每个部分都有>=k个点(即每个部分里都有>=k种颜色的节点),那么所有的Ei里必定包含这条边。(自己举几个例子试一下)

3. 所以,问题就转变为满足上述条件的边有几条 => 我们只要求出每个节点的最大子树大小Size(子树里包括这个点)即可。即这个点下半部分(包括这个点)有Size个点,上半部分有n-Size个点,Size和(n-Size)都>=k即满足条件。

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <queue>#include <algorithm>using namespace std;const int MAX=200000+9;int n,k;vector<int>map[MAX];int Size[MAX];//求子树大小void dfs(int root, int fa){    Size[root]=1;    for(int i=0;i<map[root].size();i++)    {        int u=map[root][i];        if(u==fa)            continue;        dfs(u,root);        Size[root]+=Size[u];    }}int main(){    int T;    scanf("%d",&T);    while(T--)    {        memset(Size,0,sizeof(Size));        scanf("%d%d",&n,&k);        for(int i=0;i<=n;i++)            map[i].clear();        for(int i=0;i<n-1;i++)        {            int x,y;            scanf("%d%d",&x,&y);            map[x].push_back(y);            map[y].push_back(x);        }        //减枝        if(k==1)        {            printf("%d\n",n-1);            continue;        }        dfs(1, -1);        int ans=0;        //判断满足条件点(边)的个数        for(int i=1;i<=n;i++)        {            if(Size[i]>=k&&(n-Size[i])>=k)                ans++;        }        printf("%d\n",ans);    }    return 0;}


原创粉丝点击