3 3 0 1 1 0 2 3 1 2 1 0 2 3 1 0 1 1 1 2
2 -1
dijkstr算法,做过好多这样的题了,也解释了那么多。。。这个就不详细说了吧..........
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node//实现优先队列的结构体
{
int pos,cost;
friend bool operator<(node x,node y)
{
return x.cost>y.cost;
}
};
priority_queue<node>s;
int map[205][205],vis[205],n,m;
int dijkstra(int st,int ed)
{
node temp,temp1;
temp.pos=st,temp.cost=0;
s.push(temp);
while(!s.empty())
{
temp1=temp=s.top();
s.pop();
if(temp.pos==ed)
break;
vis[temp.pos]=1;
for(int i=0;i<n;i++)
{
if(!vis[i]&&map[temp.pos][i]<100000)
{
temp.cost=temp.cost+map[temp.pos][i];
temp.pos=i;
s.push(temp);
}
temp=temp1;
}
}
if(temp.pos==ed)
return temp.cost;
else
return -1;
}
int main()
{
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(map,100,sizeof(map));
memset(vis,0,sizeof(vis));
while(!s.empty())
s.pop();
for(int i=0;i<m;i++)
{
int a,b,x;
scanf("%d %d %d",&a,&b,&x);
if(map[a][b]>x)
map[a][b]=map[b][a]=x;
}
int st,ed;
scanf("%d %d",&st,&ed);
printf("%d\n",dijkstra(st,ed));
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/su20145104009/article/details/47027455