题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6228
Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1693 Accepted Submission(s):
978
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 ∩ E2
... ∩ 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个颜色去涂这n个节点。Ei表示将所有颜色为i的结点连起来的最小边数。E1 ∩ E2 ... ∩ Ek表示E1 E2...Ek的重合边数,输出最大的E1 ∩ E2 ... ∩ Ek。
求出每个节点的子树大小(包括自己),如果子树大小大于等于k并且n-子树大小也大于等于k,ans+1。
#include<iostream>
#include<vector>
using namespace std;
#define maxn 300000
int n,k,cnt,ans,size[maxn],head[maxn];
struct edge{
int to,next;
}e[maxn];
vector<int>ve[maxn];
void add(int u,int v)
{
e[++cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt;
}
void dfs(int u,int f)
{
for(int i=0;i<ve[u].size();i++)
{
int x=ve[u][i];
if(x==f)continue;
dfs(x,u);
size[u]+=size[x];
}
if(size[u]>=k&&n-size[u]>=k)ans++;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>k;
int u,v;
for(int i=1;i<=n;i++)
{
ve[i].clear();
size[i]=1;
}
for(int i=1;i<n;i++)
{
cin>>u>>v;
add(u,v);
ve[u].push_back(v);
ve[v].push_back(u);
}
ans=0;
dfs(1,0);
cout<<ans<<endl;
}
return 0;
}
2017沈阳站 Tree
原文:https://www.cnblogs.com/chen99/p/10706615.html