标签:
题目大意:给定一个n个点n-1条的连通无向图,求从任意一点出发,在不重复经过同一点的情况下,所能走过的的边的最大权值。
解题思路:深度优先搜索。
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 struct Edge { 6 int to; 7 int dis; 8 Edge(int t = 0, int d = 0) { 9 to = t; 10 dis = d; 11 } 12 }; 13 14 const int maxn = 10005; 15 16 vector<Edge> cities[maxn]; 17 bool visited[maxn]; 18 int maxDis; 19 int dis; 20 21 void init(int n) { 22 for (int i = 1; i <= n; i++) { 23 visited[i] = false; 24 cities[i].clear(); 25 } 26 } 27 28 void dfs(int from) { 29 for (int i = 0; i < cities[from].size(); i++) { 30 Edge & e = cities[from][i]; 31 if (!visited[e.to]) { 32 visited[e.to] = true; 33 dis += e.dis; 34 maxDis = maxDis > dis ? maxDis : dis; 35 dfs(e.to); 36 visited[e.to] = false; 37 dis -= e.dis; 38 } 39 } 40 } 41 42 int main() { 43 int n, m; 44 int from, to, dis; 45 while (cin >> n >> m) { 46 init(n); 47 48 for (int i = 1; i < n; i++) { 49 cin >> from >> to >> dis; 50 cities[from].push_back(Edge(to, dis)); 51 cities[to].push_back(Edge(from, dis)); 52 } 53 54 dis = 0; 55 maxDis = 0; 56 visited[m] = true; 57 dfs(m); 58 59 cout << maxDis << endl; 60 } 61 62 return 0; 63 }
标签:
原文地址:http://www.cnblogs.com/mchcylh/p/4877249.html