标签:
深搜中与记录长度有关的题目,都差不多是这样的!
还有邻接表的写法,不够熟!
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int ans; 6 7 bool vis[10005]; 8 9 struct edge { 10 int u; 11 int v; 12 int l; 13 }; 14 15 vector <edge> graph[10005]; 16 17 void dfs(int n, int x, int temp) 18 { 19 if(ans < temp) 20 ans=temp; 21 vis[x]=1; 22 for(int i=0; i<graph[x].size(); i++) 23 { 24 if(!vis[graph[x][i].v]) 25 dfs(n, graph[x][i].v, temp+graph[x][i].l); 26 } 27 } 28 29 30 int main() 31 { 32 int n,k; 33 while(scanf("%d%d", &n, &k) != EOF) 34 { 35 ans=0; 36 int temp=0; 37 memset(graph, 0, sizeof(graph)); 38 memset(vis, 0, sizeof(vis)); 39 int u,v,l; 40 for(int i=0; i<n-1; i++) 41 { 42 edge e; 43 scanf("%d%d%d", &u, &v, &l); 44 e.u = u; 45 e.v = v; 46 e.l = l; 47 graph[u].push_back(e); //注意是双向的啊!!! 48 e.u = v; 49 e.v = u; 50 e.l = l; 51 graph[v].push_back(e); 52 } 53 54 dfs(n, k, temp); 55 printf("%d\n", ans); 56 } 57 return 0; 58 }
标签:
原文地址:http://www.cnblogs.com/dominjune/p/4504875.html