题目连接:http://poj.org/problem?id=2387
裸题最短路,不解释。。。dijkstra代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
#define MAX 1005
#define CLR(arr,v) memset(arr,v,sizeof(arr))
int h[MAX],des[MAX*4],val[MAX*4],nex[MAX*4],dis[MAX],pos;
int map[MAX][MAX];
bool inque[MAX];
struct edges
{
int end,value;
bool operator<(const edges &ed) const
{
return value > ed.value;
}
}mid;
priority_queue<edges> q;
void add(int u,int v,int f)
{
des[++pos] = v;
val[pos] = f;
nex[pos] = h[u];
h[u] = pos;
}
void init()
{
pos = 0; CLR(map,-1);
CLR(h,0); CLR(nex,0);
CLR(des,0);CLR(val,0);
fill(dis,dis+MAX,INT_MAX);
CLR(inque,0);
while(!q.empty()) q.pop();
}
int Dijkstra(int n)
{
dis[1] = 0;
mid.end = 1;
mid.value = 0;
q.push(mid);
inque[1] = true;
while(!q.empty())
{
int st = q.top().end,cost = q.top().value;
q.pop();
inque[st] = false;
for(int i = h[st]; i ;i = nex[i])
{
if(dis[ des[i] ] == INT_MAX || dis[st] + val[i] < dis[ des[i] ])
{
dis[ des[i] ] = dis[st] + val[i];
if(!inque[ des[i] ])
{
mid.end = des[i];
mid.value = dis[ des[i] ];
q.push(mid);
inque[ des[i] ] = true;
}
}
}
}
return dis[n] == INT_MAX ? -1 : dis[n];
}
int main()
{
int n,m;
while(~scanf("%d%d",&m,&n))
{
init();
int u,v,f;
for(int i = 0;i < m;++i)
{
scanf("%d%d%d",&u,&v,&f);
if(map[u][v] == -1 || f < map[u][v])
{
map[u][v] = map[v][u] = f;
}
}
for(int i = 1;i <= n;++i)
for(int j = 1;j <= n;++j)
if(map[i][j] != -1)
add(i,j,map[i][j]);
printf("%d\n",Dijkstra(n));
}
return 0;
}