L - PC is for kicking

Otvio is a calm guy with a guilty pleasure: kicking PCs. Now he is participating in a programming competition where the computers are arranged as a tree, that is, the N PCs are connected by N - 1 cables and there is only one cable path from one PC to another.

Otvio wants to kick as many PCs as possible. To do so, he will walk along a cable path, kicking all the PCs in the path. He will start at PC a, the one he will use in the contest. However, to prevent getting caught, he will not pass by PCs he already kicked nor kick any PC twice.

Laerco, knowing Otvio’s guilty pleasure, wants to know the maximum number of PCs Otvio can kick satisfying the conditions above. Remember that Otvio will kick his own PC for sure.

Input
The first line of the input consist of two integers integer N and a (1 ≤ N, a ≤ 105), the number of PCs in the contest and the number of Otvio’s PC, in this order. Each of the next N - 1 lines contains two integers u and v (1 ≤ u, v ≤ N), indicating that there is a cable connecting PCs u and v.

Output
Output a single integer - the maximum number of PCs Otvio can kick.
Example

Input
5 2
1 2
1 3
2 5
3 4

Output
4

题目的大概意思是给一个树型图,和一个起点,找去这个起点在不返回的状态下可以到达的最大的点数,
我这个方法,不算太好,用的自己想的方法,用邻接表来储存无向图;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int n,ma,head,tail;
int u[1000010],v[1000010];
int first[1000010],next[1000010],nextt[1000010],firstt[1000010];
int q[1000010],book[1000010],sum[1000010];

void bfs()
{
    while(head<tail){
        int k1=first[q[head]];
        int k2=firstt[q[head]];
        while(k1!=-1){
            int y1=v[k1];
            if(book[y1]==0)
            {
                book[y1]=1;
                q[tail]=y1;
                sum[y1]=sum[q[head]]+1;
                if(sum[y1]>ma)
                    ma=sum[y1];
                tail++;
            }
            k1=next[k1];
        }
        while(k2!=-1){
            int y2=u[k2];
            if(book[y2]==0){
                book[y2]=1;
                q[tail]=y2;
                sum[y2]=sum[q[head]]+1;
                if(sum[y2]>ma)
                    ma=sum[y2];
                tail++;
            }
            k2=nextt[k2];
        }
        head++;
    }
}

int main()
{
    int i,strx;
    scanf("%d %d",&n,&strx);

    memset(first,-1,sizeof(first));
    memset(firstt,-1,sizeof(firstt));
    memset(book,0,sizeof(book));

    for(i=1;i<n;i++){
        scanf("%d %d",&u[i],&v[i]);
        next[i]=first[u[i]];
        first[u[i]]=i;
        nextt[i]=first[v[i]];
        firstt[v[i]]=i;
    }
    head=1;
    tail=1;
    q[tail]=strx;
    book[strx]=1;
    sum[strx]=1;
    tail++;
    ma=1;
    bfs();
    printf("%d\n",ma);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值