CC lives on the tree which has N nodes.On every leaf of the tree there is an apple(leaf means there is only one branch connect this node ) .Now CC wants to get two apple ,CC can choose any node to start and the speed of CC is one meter per second.
now she wants to know the shortest time to get two apples;
Input
Thers are many cases;
The first line of every case there is a number N(2<=N<=10000)
if n is 0 means the end of input.
Next there is n-1 lines,on the i+1 line there is three number ai,bi,ci
which means there is a branch connect node ai and node bi.
(1<=ai, bi<=N , 1<=ci<=2000)
ci means the len of the branch is ci meters ;
Output
print the mininum time to get only two apple;
Sample Input
7
1 2 1
2 3 2
3 4 1
4 5 1
3 6 3
6 7 4
0
Sample Output
5
题解
- 把所有叶子节点加入优先队列(优先距离叶子近的)
- 然后bfs
- 直到相遇
- 然后取最小答案
复杂度 o(n⋅logn)
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXS=10*1024*1024;
char buf[MAXS],*ch;
void read(int &x){
while(*(++ch)<32);
for(x=0;*ch>='0';++ch) x=x*10+*ch-'0';
}
/*-------------------------------------------*/
const int INF=0x3f3f3f3f;
const int MAXN=1e4+5;
struct node{int to,cost,next;};
node dat[MAXN<<1]; int u;
int cnt[MAXN],pit[MAXN],dp[MAXN],flag[MAXN];
struct ND{int val,from,v;};
bool operator < (const ND &x,const ND &y){return x.val>y.val;}
int main()
{
fread(buf,1,MAXS,stdin);
ch=buf-1;
int n;
do{
read(n);if(!n) break;
memset(cnt ,0 ,sizeof(int)*(n+1));
memset(pit ,0 ,sizeof(int)*(n+1));
memset(dp ,-1 ,sizeof(int)*(n+1));
u=1;
for(int i=1;i<n;i++){
int x,y,c;
read(x);read(y);read(c);
dat[u]=(node){y,c,pit[x]};
pit[x]=u++;
dat[u]=(node){x,c,pit[y]};
pit[y]=u++;
cnt[x]++;
cnt[y]++;
}
priority_queue<ND> que;
for(int i=1;i<=n;i++){
if(cnt[i]==1){
que.push((ND){0,0,i});
}
}
int ans=INF;
while(!que.empty()){
ND t=que.top();que.pop();
int c=t.val;
int v=t.v;
int from=t.from;
if(dp[v]==-1){
dp[v]=c;
flag[v]=(from==0?v:flag[from]);
}else {
if(flag[from]!=flag[v])
ans=min(ans,c+dp[v]);
continue;
}
for(int i=pit[v];i;i=dat[i].next){
node &e=dat[i];
if(flag[v]!=flag[e.to]){
que.push((ND){dp[v]+e.cost,v,e.to});
}
}
}
printf("%d\n",ans);
}while(true);
return 0;
}