HDU - 6228 Tree (dfs)

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.

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

分析: 问题可以转化为求有多少条边左右两边都有k个以上的点。因为这样的边一定是符合要求的。
题目保证这是一个树,树是无向无环图,所以我们可以从一个点开始DFS搜索,进而找到每一个点左右两边的点数

代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
const int MAXN=2e5+10;
int vis[MAXN];
int num[MAXN];
int cnt;
vector<int>V[MAXN];
struct node
{
    int u;
    int v;
}poi[MAXN];
 int t,n,k,a,b,ans;
void dfs(int x)
{
    int u,v;
    num[x]=1;
  for(int i=0;i<V[x].size();i++)
  {
          u=x;
          v=V[x][i];
     /*     if(v==pre)
            continue;*/
          if(!vis[v])
          {
            vis[v]=1;
          dfs(v);
          num[u]+=num[v];
          }
  }
    if(num[u]>=k&&n-num[u]>=k)
         ans++;
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
      memset(vis,0,sizeof(vis));
        ans=0;
        scanf("%d%d",&n,&k);
        for(int i=0;i<=n;i++)V[i].clear();
         int h=n-1;
         for(int i=0;i<n-1;i++){
            scanf("%d%d",&poi[i].u,&poi[i].v);
            V[poi[i].u].push_back(poi[i].v);
            V[poi[i].v].push_back(poi[i].u);
         }
         vis[1]=1;
        dfs(1);
        printf("%d\n",ans);
    }
    return 0;
}

 



posted @ 2017-12-04 20:37  hinata_hajime  阅读(199)  评论(0编辑  收藏  举报