Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
树形DP,两次DFS,求树的直径#include <stdio.h> #include <string> #include <string.h> #include <queue> #include <stack> #include <map> #include <iostream> #include <stdlib.h> #include <math.h> #include <algorithm> #define inf 0x3f3f3f3f #define mem0(x , y) memset(x , y , sizeof(x)) #define ll long long using namespace std; struct node{ int s, e , w ,next ; } ; node Edge[100000] ; int head[50000] , cnt = 0 ; void add(int s,int e,int w){ Edge[cnt].s = s ; Edge[cnt].e = e ; Edge[cnt].w = w ; Edge[cnt].next = head[s] ; head[s] = cnt ++ ; } int dis[100000][3] ; void dfs(int s , int pre) { int f = 0 ; int mx = 0 , ms = -1 , mi = -1 ; for(int i=head[s] ; i!=-1 ; i=Edge[i].next){ int v = Edge[i].e ; if(pre == v) continue ; f ++ ; dfs(v, s) ; if(mx <= dis[v][0] + Edge[i].w) { ms = mx ; mx = dis[v][0] + Edge[i].w ; mi = v ; } } dis[s][0] = mx ; dis[s][1] = ms ; dis[s][2] = mi ; ///printf("dfs %d -> %d\n" , s, dis[s][0]) ; } int ans = 0 ; void dfs2(int s,int pre){ ///printf("%d -> %d\n" , s, dis[s][0]) ; ans = max(ans , dis[s][0]) ; for(int i=head[s] ; i!=-1 ; i=Edge[i].next){ int v = Edge[i].e ; if(pre == v) continue ; if(dis[s][2] == v){ if(dis[s][0] - Edge[i].w <= Edge[i].w + dis[s][1]){ dis[v][0] = Edge[i].w + dis[s][1] ; dis[v][2] = s ; } } else { dis[v][0] = Edge[i].w + dis[s][0] ; dis[v][2] = s ; } dfs2(v , s) ; } } int main(){ ///freopen("1" , "r" ,stdin) ; int n , m ; scanf("%d%d",&n,&m) ; mem0(head , -1) ; int ta , tb ,tc ; char td[4]; for(int i=0;i<m;i++){ scanf("%d%d%d%s",&ta,&tb,&tc,td) ; add(ta , tb ,tc ) ; add(tb , ta ,tc ) ; } dfs(1 , -1) ; dfs2(1 , -1) ; printf("%d\n",ans) ; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator