UVALive - 8080 (vector用法)

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

 

 

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 1100
vector<int> G[MAXN];
int ans[MAXN];
int n,k;
bool cmp(int x,int y)
{
    return x>y;
}
void init()
{
    int i;
    for(i=1;i<=MAXN;i++)
    {
       G[i].clear();
    }
    memset(ans,-1,sizeof(ans));
}
int dfs(int u,int fa)
{
      int i;
      int v;
      int sum=1;
      int b[MAXN];
      memset(b,0,sizeof(b));           //这个只是强调叶子结点而已
      if(G[u].size()==1&&G[u][0]==fa) //双向边vector的用法
      return sum;                     //这个fa就实现了由上到下。
      int j=0;
      for(i=0;i<G[u].size();i++)
      if(G[u][i]!=fa)
      {
            v=G[u][i];
            b[j++]=dfs(v,u);
      }
      sort(b,b+j,cmp);
      if(j>=k)
      {
          for(i=0;i<k;i++)
          sum+=b[i];
      }
      return sum;
}
int main()
{
    int t;
    scanf("%d",&t);
    int Cas=1;
    while(t--)
    {
        init();
        int u,v;
        scanf("%d%d",&n,&k);
        n--;
        while(n--)
        {
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        int sum=dfs(1,-1);
        printf("Case %d: %d\n",Cas++,sum);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值