1. 程式人生 > >HDU 6228/2017ACM/ICPC 瀋陽 Tree 【DFS】

HDU 6228/2017ACM/ICPC 瀋陽 Tree 【DFS】

Tree

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

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 1to n. If you cannot understand the concept of a tree here, please omit thisproblem.
Now we decide to colour its nodes with k distinct colours, labelled from 1 tok. Then for each colour i = 1, 2, · · · , k, define Ei as the minimum subset ofedges connecting all nodes coloured by i. If there is no node of the treecoloured by a specified colour i, Ei will be empty.
Try to decide a colour scheme to maximize the size of E1 ∩ E2 · · · ∩ Ek, andoutput its size.

Input

The first line of input contains an integer T (1 ≤ T ≤ 1000), indicating the totalnumber of test cases.
For each case, the first line contains two positive integers n which is thesize of the tree and k (k ≤ 500) which is the number of colours. Each of thefollowing n - 1 lines contains two integers x and y describing an edge betweenthem. 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種顏色對節點染色,每種顏色對應一個集合,表示將樹上所有這種顏色的點連起來經過的最小邊。現在需要求所有集合取交集後的大小。

【思路】

假設我們取定1為根節點。

顯然要是結果最大,相同顏色應該要儘可能分佈在樹的頂部和底部。

雖然我們需要考慮的是邊,但是我們可以轉化為對每個節點去考慮。令在這個節點的兩側每種顏色均有分佈,那麼一定會有一條公共邊。

先用DFS求出每個點的子孫節點個數(包括自身),假設為x,那麼它的上面點的個數為n-x,只要x>=k&&(n-x)>=k即能滿足上面的條件。

我們只要列舉每個點,滿足條件點的個數即為答案。

#include <cstdio>
#include <cmath>
#include <set>
#include <cstring>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define rush() int T;scanf("%d",&T);while(T--)

typedef long long ll;
const int maxn = 200005;
const ll mod = 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-9;

int n,k,ans;
int num[maxn];
vector<int>vec[maxn];

void dfs(int u,int pre)
{
    num[u]=1;
    for(int i=0;i<vec[u].size();i++)
    {
        int v=vec[u][i];
        if(v==pre) continue;
        dfs(v,u);
        num[u]+=num[v];
        if(num[v]>=k&&n-num[v]>=k) ans++;
    }
}

int main()
{
    int u,v;
    rush()
    {
        mst(num,0);
        scanf("%d%d",&n,&k);
        for(int i=1;i<=n;i++)
        {
            vec[i].clear();
        }
        for(int i=1;i<n;i++)
        {
            scanf("%d%d",&u,&v);
            vec[u].push_back(v);
            vec[v].push_back(u);
        }
        ans=0;
        dfs(1,-1);
        printf("%d\n",ans);
    }
    return 0;
}