Description
Farmer John's field has N (2 <= N <= 1000) landmarks in it, uniquely numbered 1..N. Landmark 1 is the barn; the apple tree grove in which Bessie stands all day is landmark N. Cows travel in the field using T (1 <= T <= 2000) bidirectional cow-trails of various lengths between the landmarks. Bessie is not confident of her navigation ability, so she always stays on a trail from its start to its end once she starts it.
Given the trails between the landmarks, determine the minimum distance Bessie must walk to get back to the barn. It is guaranteed that some such route exists.
Input
* Lines 2..T+1: Each line describes a trail as three space-separated integers. The first two integers are the landmarks between which the trail travels. The third integer is the length of the trail, range 1..100.
Output
Sample Input
5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
Sample Output
90
Hint
There are five landmarks.
OUTPUT DETAILS:
Bessie can get home by following trails 4, 3, 2, and 1.
裸的Dijkstra,重边对堆优化的写法没有影响,一开始想搜到n就跳出,不知为啥老是wa,就放弃了,老老实实全都一边,nlgn的复杂度还是可以接受的。代码如下:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#define m 1000000
using namespace std;
typedef structnode
{
int u,v,c;
bool operator<(const node&t)
const
{
return c>t.c;
}
node(int uu=0,int cc=0):u(uu),c(cc){}
}node;
typedef structedge
{
int v,c;
edge(int vv=0,int cc=0):v(vv),c(cc){}
}edge;
int n;
int dij[1005];
bool r[1005];
vector<edge> E[1005];
int Dijkstra(int st)
{
memset(r,false,sizeof(r));
for(int i=1;i<=n;++i)
dij[i]=m;
priority_queue<node> q;
q.push(node(st,0));
dij[st]=0;
node t;
while(!q.empty())
{
t=q.top(),q.pop();
int u=t.u;
if(r[u])continue;
r[u]=true;
for(int i=0;i<E[u].size();++i)
{
int v=E[u][i].v,c=E[u][i].c;
if(!r[v]&&(dij[u]+c<dij[v]))
{ dij[v]=dij[u]+c;
q.push(node(v,dij[v]));
}
}
}
}
int main()
{
int t,x,y,z;
cin>>t>>n;
for(int i=0;i<t;++i)
{
cin>>x>>y>>z;
if(x==y)continue;
E[x].push_back(edge(y,z));
E[y].push_back(edge(x,z));
}
Dijkstra(1);
cout<<dij[n]<<endl;
return 0;
}