CC On The Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)Total Submission(s): 1726 Accepted Submission(s): 617
Problem Description
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;
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 ;
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
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cstdlib>
#define min(a , b) (a > b ? b : a)
#define INF 0x3f3f3f3f
using namespace std;
int n, num;
struct node {
int u;
int v;
int w;
int next;
};
int head[11000], vis[11000], cnt, du[11000];
node edge[22000];
struct mod{
int x, step;
friend bool operator < (mod s1, mod s2)
{
return s1.step > s2.step;
}
};
void add(int u, int v, int w){
edge[cnt].u = u;
edge[cnt].v = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt++;
}
bool judge(mod s){
if(vis[s.x]) return 0;
if(s.step > num) return 0;
return 1;
}
mod s1,temp;
int bfs(int x){
s1.x = x;
s1.step = 0;
priority_queue<mod>q;
q.push(s1);
memset(vis, 0 ,sizeof(vis));
vis[s1.x] = 1;
while(!q.empty()){
s1 = q.top();
q.pop();
int u = s1.x;
for(int i = head[u]; i != -1; i = edge[i].next){
int u = edge[i].u;
int v = edge[i].v;
int w = edge[i].w;
temp.x = v;
temp.step = s1.step + w;
if(!judge(temp)) continue;
if(du[v] == 1)
return temp.step;
vis[temp.x] = 1;
q.push(temp);
}
}
return num;
}
int main (){
while(scanf("%d", &n),n){
memset(du, 0 ,sizeof(du));
memset(head, -1, sizeof(head));
cnt = 0;
for(int i = 0; i < n - 1; ++i){
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
add(v, u, w);
du[u]++;
du[v]++;
}
num = INF;
for(int i = 1 ; i <= n; ++i){
if(du[i] == 1){
int sum = bfs(i);
num = min(num, sum);
}
}
printf("%d\n", num);
}
return 0;
}