貌似还是树状DP,貌似我还不会,还是用搜索搜的。
如果纯粹用优先队列搜,会超时的。需要标记到达某个节点后的最小长度,如果下一次搜到这个点长度比这个点存的大,就不需要入队了,入了也白入= =。。
#include <queue>
#include <stack>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <limits.h>
#include <string.h>
#include <string>
#include <algorithm>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define BUG puts("here!!!")
using namespace std;
const int MAX = 10010;
struct NODE{ int len,to; NODE* next;};
struct A{int len,u;};
NODE node[MAX*2],*p[MAX];
int a[MAX],cnt;
int b[MAX];
bool used[MAX];
void init()
{
cnt = 0;
fill(b,b+MAX,INT_MAX);
memset(used,false,sizeof(used));
memset(p,0,sizeof(p));
memset(a,0,sizeof(a));
memset(node,0,sizeof(node));
}
void Add(int u,int v,int len)
{
node[cnt].to = v;
node[cnt].len = len;
node[cnt].next = p[u];
p[u] = &node[cnt++];
}
priority_queue<A> q;
bool operator<(A a,A b)
{
return a.len > b.len;
}
int BFS(int x)
{
while( !q.empty() ) q.pop();
A tmp; tmp.u = x; tmp.len = 0;
q.push(tmp);
while( !q.empty() )
{
int now = q.top().u;
int len = q.top().len;
q.pop();
if( a[now] == 1 && now != x ) return len;
NODE *head = p[now];
while( head != NULL )
{
A tmp; tmp.u = head->to;
tmp.len = len+head->len;
if( tmp.len < b[head->to] )
{
b[head->to] = tmp.len;
q.push(tmp);
}
head = head->next;
}
}
return INT_MAX;
}
int main()
{
int n,x,y,len;
while( ~scanf("%d",&n) && n )
{
init();
for(int i=0; i<n-1; i++)
{
scanf("%d%d%d",&x,&y,&len);
a[x]++; a[y]++;
Add(x,y,len);
Add(y,x,len);
}
int mmin = INT_MAX;
for(int i=1; i<=n; i++)
if( a[i] == 1 )
{
b[i] = 0;
used[i] = true;
int ans = BFS(i);
mmin = min(mmin,ans);
}
printf("%d\n",mmin);
}
return 0;
}