标签:des blog http io os 使用 ar for strong
There are several test cases in the input
A test case starts with two numbers N and K. (1<=N<=10000, 1<=K<=N). The cities is denoted from 1 to N. K is the capital.
The next N-1 lines each contain three numbers X, Y, D, meaning that there is a road between city-X and city-Y and the distance of the road is D. D is a positive integer which is not bigger than 1000.
Input will be ended by the end of file.
3 1 1 2 10 1 3 20
20
// Problem#: 1024 // Submission#: 2973318 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <iostream> #include <stdio.h> #include <map> #include <vector> #include <cstring> using namespace std; typedef struct node { int from; int edge; int to; } Node; int longest; map<int, vector<Node> > nodes; bool visited[10001]; //深度优先搜索 void DFS(int k, int distance) { bool deeper = false; //标记是否到达了叶子节点 for (int i = 0; i < nodes[k].size(); i++) { if (visited[nodes[k].at(i).to] == false) { visited[nodes[k].at(i).to] = true; deeper = true; DFS(nodes[k].at(i).to, distance + nodes[k].at(i).edge);//此步很关键 } } //如果到达了叶子节点则对该路径中的权值之和与最大距离比较 if (!deeper && distance > longest) { longest = distance; } } int main() { int n, k; while (scanf("%d %d", &n, &k) != EOF) {//刚开始超时原来是忘了加 != EOF!!!!! memset(visited, false, sizeof(visited)); //使用map容器建立邻接链表 for (int i= 0; i < n-1; i++) { int from, edge, to; scanf("%d %d %d", &from, &to, &edge); Node temp; temp.from = from; temp.edge = edge; temp.to = to; nodes[from].push_back(temp); temp.from = to; temp.to = from; nodes[to].push_back(temp); } longest = 0; int distance = 0; visited[k] = true; DFS(k, distance); cout << longest << endl; nodes.clear(); } return 0; }
标签:des blog http io os 使用 ar for strong
原文地址:http://www.cnblogs.com/xieyizun-sysu-programmer/p/4007868.html