[sicily online]1024. Magic Island

來源:互聯網
上載者:User
Constraints

Time Limit: 1 secs, Memory Limit: 32 MB

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.

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.

Output

One number per line for each test case, the longest distance the king can go.

Sample Input

3 11 2 101 3 20

Sample Output

20

分析:

我是用隊列實現的廣度優先,時間是0.4s,但是別人用深度優先就0.15s,必須把所有葉子節點都遍曆到啊,為什麼時間會差這麼多呢。。

#include<iostream>#include <iomanip>#include<stdio.h>#include<cmath>#include<iomanip>#include<list>#include <map>#include <vector>#include <string>#include <algorithm>#include <sstream>#include <stack>#include<queue>#include<string.h>using namespace std;typedef struct NODE{int distanceTotal;bool flag;vector<struct LINE> child;//line看不到}node;typedef struct LINE{int another;int value;}line;int main(){int n,root;while(scanf("%d%d",&n,&root)!=EOF){root--;//以0開始map<int,node> gra;for(int i=0;i<n-1;i++){//初始化圖int row,col,distance;//cin>>row>>col>>distance;scanf("%d%d%d",&row,&col,&distance);row--;col--;line li1={col,distance};line li2={row,distance};gra[row].child.push_back(li1);gra[row].distanceTotal=0;gra[row].flag=false;gra[col].child.push_back(li2);gra[col].distanceTotal=0;gra[col].flag=false;}//end for iqueue<int> qu;//用隊列,廣度優先qu.push(root);gra[root].flag=true;int max=0;while(!qu.empty()){int index=qu.front();gra[index].flag=true;qu.pop();for(vector<line>::iterator ite=gra[index].child.begin();ite!=gra[index].child.end();ite++){if(gra[ite->another].flag)continue;gra[ite->another].distanceTotal=gra[index].distanceTotal+ite->value;if(gra[ite->another].child.size()==1){if(max<gra[ite->another].distanceTotal)max=gra[ite->another].distanceTotal;}else qu.push(ite->another);}}//end whilecout<<max<<endl;}//end while cin}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.