problemcutter

导航

SPOJ Problem 1437:Longest path in a tree

求树的最长链,BFS和DFS都可以,时间复杂度O(n)

#include<cstdio>
#include<cstring>
int tot,vt[20005],nxt[20005],a[20005];
bool vis[10005];
int n,i,j,xx,yy,s,ma,r;
void search(int x,int dep){
    int p;
    vis[x]=1;
    if (dep>ma){ma=dep;r=x;}
    p=a[x];
    while(p){
        if (!vis[vt[p]]){
            search(vt[p],dep+1);
        }
        p=nxt[p];
    }
}
void addnode(int x,int y){vt[++tot]=y;nxt[tot]=a[x];a[x]=tot;    }
int main (){
    scanf("%d",&n);
    for (i=1;i<n;i++){
        scanf("%d%d",&xx,&yy);
        addnode(xx,yy);
        addnode(yy,xx);
    }
    search(1,0);
    ma=0;
    memset(vis,0,n+1);
    search(r,0);
    printf("%d",ma);
}

 

posted on 2015-03-14 10:22  problemcutter  阅读(259)  评论(0编辑  收藏  举报