WOJ1024-Exploration

来源:互联网 发布:keras tensorflow关系 编辑:程序博客网 时间:2024/05/21 07:11

Tom is an explorer and now he is in a mysterious cave. He finds that there are lots of rooms in it. You are ensured that these rooms

are connected together by some roads and there is only one way between any two rooms. That is, all the rooms are connected as a
tree.
Now, Tom wants to travel all the rooms in this mysterious cave. The roads and rooms can be passed more than once. But there are
too many rooms here and he doesn?t want to waste too much time and wants to find a walking sequence which can minimum the distance
he walks. Note, Tom can select any room in the cave as the start point in his exploration.
Given the distance of roads in the cave, please write a program to calculate the minimum distance Tom has to go in his exploration.

输入格式

Standard input will contain multiple test cases. The first line of the input if a single integer T (1 <= T <= 50) which is the number

of test cases.
Each test case starts with an integer N (2 <= N <= 50000), which is the number of the rooms. The following N - 1 lines contains three integers each, u (1 <= u <= N), v (1 <= v <= N) and d (1 <= d <= 2000). u and v is the serial number of the rooms and d is the
distance between Room u and Room v .Note that, the serial numbers of the rooms start at 1.

输出格式

Results should be directed to standard output. Start each case with "Case #:" on a single line, where # is the case number starting

from 1. Two consecutive cases should be separated by a single blank line. No blank line should be produced after the last test case.
For each test case, print a line containing the minimum distance Tom should go.

样例输入

221 2 331 2 31 3 4

样例输出

Case 1:3Case 2:7
#include<iostream>#include<cstdio>#include<cstring>#include<vector>#include<queue>using namespace std;struct node{int v,d;};int n,dist[50001];vector<node> tree[50001];int zuiyuan(int s){int vis[n+5],i,max=0,maxi=0;memset(vis,0,sizeof(vis));queue<int> q;q.push(s);vis[s]=true;dist[s]=0;while(!q.empty()){int temp=q.front();q.pop();for(i=0;i<tree[temp].size();i++)if(!vis[tree[temp][i].v]&&(dist[temp]+tree[temp][i].d<dist[tree[temp][i].v])){dist[tree[temp][i].v]=dist[temp]+tree[temp][i].d;q.push(tree[temp][i].v);vis[tree[temp][i].v]=true;}}for(i=1;i<=n;i++)if(max<dist[i]){max=dist[i];maxi=i;}return maxi;} int main(){int t,ti,a,b,c,i,ans,maxa,maxb;cin>>t;for(ti=1;ti<=t;ti++){cin>>n;for(i=1;i<=n;i++)tree[i].clear();ans=0;for(i=0;i<n-1;i++){cin>>a>>b>>c;node no1,no2;no1.v=b;no1.d=c;no2.v=a;no2.d=c;tree[a].push_back(no1);tree[b].push_back(no2);ans=ans+2*c; } for(i=1;i<=n;i++)dist[i]=0x7fffffff;maxa=zuiyuan(1);for(i=1;i<=n;i++)dist[i]=0x7fffffff;maxb=zuiyuan(maxa);if(ti!=1)puts("");printf("Case %d:\n",ti);cout<<ans-dist[maxb]<<endl;}return 0;} 



原创粉丝点击