ACM暑期集训28

先补一道题,后面再补:
Christmas is coming and Bob wants to decorate his tree. The tree has N nodes. 1 is the root. He thinks a tree is beautiful if each node has exactly K child (immediate descendant) nodes (of course except the leaf nodes). He wants to remove zero or more nodes of the tree so that the property holds. If we delete a non-leaf node, the whole subtree rooted in that node, will be removed from the tree. What is the maximum number of nodes the tree can have after deleting some (possibly zero) nodes so that it has the above properties?

 

Input

 

The first line contains T (1 ≤ T ≤ 1000) , number of test cases. For each test case, the first line contains two space-separated integers N ( 1 ≤ N ≤ 1000) and K (1 ≤ K ≤ 100) . Each of the next N − 1 lines contains two integers U and V (1 ≤ U, V ≤ N), denoting an edge.

 

Output

 

For each case, print the case number and the answer.

 

Sample Input

 

2

6 3

1 2

1 3

1 4

4 5

4 6

6 4

1 2

1 3

1 4

4 5

4 6

 

Sample Output

Case 1: 4

Case 2: 1

 

分析:用dp[x]表示以x为根结点满足题意的子结点个数,如果该结点子结点个数小于K,那么该结点就要删除,如果等于K那么保留,如果大于K,那么我应该保留子结点中结点个数前K大的子结点,因为他们的子结点也有可能符合题意

 

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn=1010;
vector<int> a[maxn];
int dp[maxn];
int vis[maxn],k;

bool cmp(int a,int b)
{
	return a>b;
}

int dfs(int x)
{
	int cnt=0;
	dp[x]=1;
	for(int i=0;i<a[x].size();i++)
	{
		if(!vis[a[x][i]]) cnt++;
	}
	if(cnt==k) {
		for(int i=0;i<a[x].size();i++)
		{
			if(!vis[ a[x][i] ])
			{
				vis[ a[x][i] ]=1;
				dp[x]+=dfs(a[x][i]);
			}
		}
	}
	else if (cnt>k) {
		int num[maxn];
		int te=0;
		for(int i=0;i<a[x].size();i++)
		{
			if(!vis[ a[x][i] ])
			{
				vis[ a[x][i] ]=1;
				num[te++]=dfs(a[x][i]);
			}
		}
		sort(num,num+te,cmp);
		for(int i=0;i<k;i++)
			dp[x]+=num[i];
	}
	return dp[x];
}

int main()
{
	int t;
	scanf("%d",&t);
	for(int j=1;j<=t;j++)
	{

		int n;
		scanf("%d%d",&n,&k);
		for(int i=0;i<=n;i++) a[i].clear();
		memset(vis,0,sizeof(vis));
		for(int i=1;i<n;i++)
		{
			int aa,b;
			scanf("%d%d",&aa,&b);
			a[aa].push_back(b);
			a[b].push_back(aa);
		}
		vis[1]=1;
		dfs(1);
		printf("Case %d: %d\n",j,dp[1]);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值