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;
}

猜你喜欢

转载自blog.csdn.net/xigongdali/article/details/82047864