hdu 4707 Pet

http://acm.hdu.edu.cn/showproblem.php?pid=4707

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

#define MAXN 200005

int sum;
int D;
int dis[MAXN];
bool vis[MAXN];

struct Edge//邻接表存储结构
{
    int to,next;
} edge[MAXN];
int head[MAXN],tot;

void addedge(int u,int v)
{
    edge[tot].to=v;
    edge[tot].next=head[u];
    head[u]=tot++;
}

void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
}

void bfs(int u)
{

    queue<int> myQueue;
    myQueue.push(0);
    dis[0]=0;
    vis[0]=true;
    ++sum;
    int i;
    int v;

    while(!myQueue.empty())
    {
        v=myQueue.front();
        myQueue.pop();
        for(i=head[v]; i!=-1; i=edge[i].next)
        {
            if(dis[v]+1<=D&&!vis[edge[i].to])
            {
                myQueue.push(edge[i].to);
                dis[edge[i].to]=dis[v]+1;
                vis[edge[i].to]=true;
                ++sum;
            }
        }
    }

}

int main()
{

    int T;
    int N;
    int x,y;
    int i;

    scanf("%d",&T);

    while(T--)
    {
        scanf("%d%d",&N,&D);

        init();
        for(i=1; i<N; ++i)
        {
            scanf("%d%d",&x,&y);
            addedge(x,y);
            addedge(y,x);
        }
        sum=0;

        bfs(0);

        printf("%d\n",N-sum);
    }

    return 0;
}

你可能感兴趣的:(hdu 4707 Pet)