2017 ACM/ICPC 沈阳 L题 Tree

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
题解:考虑某条边,则只要两边的2个顶点都大于等于k,则连边时一定会经过这条边,ans++;

参看代码:
#include<bits/stdc++.h>
using namespace std;
#define clr(a,b,n) memset((a),(b),sizeof(int)*n)
typedef long long ll;
const int maxn = 2e5+10;
int n,k,ans,num[maxn];
vector<int> vec[maxn];

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

int main()
{
    int T,u,v;
    scanf("%d",&T);
	while(T--)
    {
        scanf("%d%d",&n,&k);
        clr(num,0,n+1); ans=0;
        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);
        }
        dfs(1,-1);
        //for(int i=1;i<=n;++i) cout<<num[i]<<endl;
        printf("%d\n",ans);
    }
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/songorz/p/9784973.html