Sicily-1024
一. 题意:
有n个节点,n-1条边,并且任意两个节点都连通。模拟一下,实际上是一棵树的便利,求从特定根节点出发最长路径的值。这里用了广搜。
二. 每个节点只有两条邻接边,每个节点用一个vector来存储这些边。还有isVisited数组保证一条路径中一个节点只能经过一次。
三.
1 // 2 // main.cpp 3 // sicily-1024 4 // 5 // Created by ashley on 14-10-13. 6 // Copyright (c) 2014年 ashley. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <vector> 11 using namespace std; 12 typedef struct 13 { 14 int left; 15 int right; 16 int weight; 17 }edge; 18 vector<edge> route; 19 vector<edge> adj[10001]; 20 bool isVisited[10001]; 21 void breadthSearch(int source, int &length, int pathLength) 22 { 23 isVisited[source] = true; 24 for (int i = 0; i < (int)adj[source].size(); i++) { 25 if (isVisited[adj[source][i].right] == false || isVisited[adj[source][i].left] == false) { 26 if (pathLength + adj[source][i].weight > length) { 27 length = pathLength + adj[source][i].weight; 28 } 29 if (isVisited[adj[source][i].right] == false) { 30 breadthSearch(adj[source][i].right, length, pathLength + adj[source][i].weight); 31 } 32 if (isVisited[adj[source][i].left] == false) { 33 breadthSearch(adj[source][i].left, length, pathLength + adj[source][i].weight); 34 } 35 } 36 } 37 } 38 int main(int argc, const char * argv[]) 39 { 40 int nodeNum, capital; 41 while (cin >> nodeNum >> capital) { 42 for (int i = 0; i < 10001; i++) { 43 adj[i].clear(); 44 isVisited[i] = false; 45 } 46 //memset(adj, 0, sizeof(adj)); 47 //memset(isVisited, 0, sizeof(isVisited)); 48 int l, r, w; 49 for (int i = 0; i < nodeNum - 1; i++) { 50 cin >> l >> r >> w; 51 adj[l].push_back(edge{l, r, w}); 52 adj[r].push_back(edge{l, r, w}); 53 } 54 int longest = 0; 55 breadthSearch(capital, longest, 0); 56 cout << longest << endl; 57 } 58 return 0; 59 }
源代码
posted on 2014-12-08 19:39 ashleyblog 阅读(159) 评论(0) 编辑 收藏 举报