L - Tree HDU - 6228

L - Tree HDU - 6228

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个节点的树,n-1条边,k种颜色.现在给n个节点上色.上完色后,每种颜色用过边连成一个联通块,求所有的颜色联通块都要经过那些边时,边的个数(尽可能大).

  • 解题思路(dfs):我们可一用一个dfs遍历这棵树,每个节点记录两个值,一个是如果走这个节点那么一共能走多少个节点(m),那么n-m即为另一端的节点个数.只要保证min(m,n-m)>k,那么走向这个节点的边就一定存在.时间复杂度O(n);

#include<bits/stdc++.h>
#define mk make_pair
#define endl '\n'
#define pb push_back
#define _ ios::sync_with_stdio(false)
using namespace std;
typedef long long ll;
const double EPS = 1e-10;
const double PI = acos(-1);
bool SUBMIT = 1;
const int inf =2e5+10;
int n,k,h[inf],ans;
vector<int> g[inf];
void fun1(int a,int b){
	g[a].pb(b);
	g[b].pb(a);
}
int dfs(int m){
	if(h[m]){
		return 0;
	}
	int c=0;h[m]=1;
	for(int i=0;i<g[m].size();i++){
		c+=dfs(g[m][i]);
	}
	c++;
	if(min(c,n-c)>=k)ans++;
	return c;
}
int main()
{
	if(!SUBMIT)freopen("i.txt","r",stdin);else _;	
	int t;cin>>t;
	while(t--){
		cin>>n>>k;
		for(int i=0;i<=n;i++){g[i].clear();h[i]=0;}
		for(int i=0;i<n-1;i++){
			int a,b;cin>>a>>b;
			fun1(a,b);
		}
		ans=0;
		dfs(1);
		cout<<ans<<endl;
	}
	return 0;
}
posted @ 2018-10-13 11:02 i-Curve 阅读( ...) 评论( ...) 编辑 收藏
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值