sicily 1024 鄰接矩陣與深度優先搜索解題

Description
There are N cities and N-1 roads in Magic-Island. You can go from one city to any other. One road only connects two cities. One day, The king of magic-island want to visit the island from the capital. No road is visited twice. Do you know the longest distance the king can go.
Input

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.node

The next N-1 lines each contain three numbers XYD, 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.ios

Output
One number per line for each test case, the longest distance the king can go.
Sample Input
 Copy sample input to clipboard
3 1
1 2 10
1 3 20
Sample Output
20

Problem Source: ZSUACM Team Member

// 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;
}                                 
相關文章
相關標籤/搜索