码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 6228 Tree(思维 DFS)

时间:2017-11-18 22:01:30      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:efi   col   nec   cin   maximum   can   题解   connect   int   

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

题意:

给了一个无向图,题目保证了是连通图,可以看成一棵树。然后给N个结点分别涂上K种颜色,所有相同颜色的结点连在一起构成一个边集,问所有边集的交集最大是多少?

题解:

可以对边进行考虑,边连结两侧,那么只有当两侧的结点数量>=k时才可能满足该边是所有边集的公共边。统计一下满足这种条件这种公共边的数量就是答案了。

#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
int ans;
const int maxn=2e5+5;
int num[maxn];
vector<int> G[maxn];
int n,k;
int dfs(int u,int pre)
{
    num[u]=1;//结点本身也算进去
    for(int i=0;i<G[u].size();i++)
    {
        int v=G[u][i];
        if(v==pre)
            continue;
        dfs(v,u);
        num[u]+=num[v];
        if(num[v]>=k&&n-num[v]>=k)
            ans++;
    }
    return ans;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        memset(num,0,sizeof(num));
        cin>>n>>k;
        for(int i=1;i<=n;i++)
            G[i].clear();
        for(int i=0;i<n-1;i++)
        {
            int u,v;
            cin>>u>>v;
            G[u].push_back(v);
            G[v].push_back(u);
        }
        ans=0;
        cout<<dfs(1,-1)<<endl;
    }
    return 0;
}

HDU 6228 Tree(思维 DFS)

标签:efi   col   nec   cin   maximum   can   题解   connect   int   

原文地址:http://www.cnblogs.com/orion7/p/7857823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!