Graph Theory for sdut3045-(Multi-tree longest chain) and sdut3045 Graph Theory
Fan Zhi Graph Theory Time Limit: 1000 MS Memory limit: 65536 K Description
FF is a master of graph theory, so I want to figure out a graph without any flow problems.
Returns the length of the longest chain of a tree.
Multiple Input groups. The first Act n (1 <= n <= 100000) entered in each group represents the number of nodes. The node number ranges from 1 to n. The next n-1 rows have two positive integers u, v, represents an edge connecting u and v. Make sure that each group of data is a tree.
For each group of data output, a positive integer represents the answer.
Sample Input
121 2
Sample output
12
Prompt source zmxdfs search
#include <cstdio>#include <cstring>#include <algorithm>using namespace std ;struct node{ int v ; int next ;}p[1000000];int head[110000] , cnt , vis[110000] ;int ans , max1[110000] ;void add(int u,int v){ p[cnt].v = v ; p[cnt].next = head[u] ; head[u] = cnt++ ; p[cnt].v = u ; p[cnt].next = head[v] ; head[v] = cnt++ ;}void dfs(int u,int num){ int i , j , v , flag = 0 , k1 = -1 , k2 = -1 ; for(i = head[u] ; i != -1 ; i = p[i].next) { v = p[i].v ; if( !vis[v] ) { flag = 1 ; vis[v] = num+1 ; dfs(v,num+1) ; } } if( flag == 0 ) { max1[u] = 1 ; return ; } for(i = head[u] ; i != -1 ; i = p[i].next) { v = p[i].v ; if( vis[u]+1 != vis[v] ) continue ; if( k1 == -1 ) k1 = max1[v] ; else { if( max1[v] > k1 ) { k2 = k1 ; k1 = max1[v] ; } else if( max1[v] > k2 ) k2 = max1[v] ; } } max1[u] = k1 + 1 ; ans = max( ans,max1[u] ) ; if( k2 == -1 ) return ; else { ans = max( ans,k1+k2+1 ) ; } return ;}int main(){ int n , u , v , i ; while( scanf("%d", &n) != EOF ) { cnt = 0 ; ans = 2 ; memset(head,-1,sizeof(head)) ; memset(vis,0,sizeof(vis)) ; if(n == 1) { printf("1\n") ; continue ; } for(i = 1 ; i < n ; i++) { scanf("%d %d", &u, &v) ; add(u,v) ; } vis[1] = 1 ; dfs(1,1); printf("%d\n", ans) ; } return 0;}