您的位置:首页 > 其它

HDU 3790最短路径问题 dijikstra算法

2016-04-14 22:08 399 查看
//赛码网 3790

*

输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。

(1

3 2

1 2 5 6

2 3 4 5

1 3

0 0

输出 一行有两个数, 最短距离及其花费。

9 11

*/

#include<iostream>
using namespace std;
const int INFINITY = 0xffffff;
const int MAX = 1000+10;
int n,m;
int Dist[MAX][MAX],Cost[MAX][MAX];
int min_dist,min_cost;
int beg,endd;

void dijikstra()
{
int i,j;
bool visit[MAX];
int dist[MAX];
int cost[MAX];
int min,tempv;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dist[j] = Dist[beg][j];
cost[j] = Cost[beg][j];
visit[j] = false;
}
}
dist[beg] = 0;
visit[beg] = true;
//cost[beg] = 0;
for(i=0;i<m;i++)
{
//找最短的一条路
min = INFINITY;
tempv = beg;
for(j=1;j<=n;j++)
{
if(!visit[j] && min>dist[j])
{
tempv = j;
min = dist[j];

}
}
visit[tempv] = true;
for(j=1;j<=n;j++)
{
if(!visit[j] && min + Dist[tempv][j] < dist[j])
{
dist[j] = min+Dist[tempv][j];
cost[j] = cost[tempv] + Cost[tempv][j];
}
else if(!visit[j] && min + Dist[tempv][j] == dist[j])
{
if(cost[j]>cost[tempv] + Cost[tempv][j])
cost[j] = cost[tempv]+Cost[tempv][j];
}
}
if(visit[endd])
{
min_dist = dist[endd];
min_cost = cost[endd];
return;
}
}
min_cost = cost[endd];
min_dist = dist[endd];
return;
}
int main()
{
int a,b,d,p;
int i,j;
while(scanf("%d%d",&n,&m)) //需要注意这里,最好用scanf,不要用cin
{
if(n==0 && m==0)
break;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
Dist[i][j] = Dist[j][i]= INFINITY;
Cost[i][j] =Cost[j][i] = INFINITY;
}
}
for(i=0;i<m;i++)
{
scanf("%d%d%d%d",&a,&b,&d,&p);
if(Dist[a][b]>d)
{
Dist[a][b] = Dist[b][a] = d;
Cost[a][b] = Cost[b][a] = p;
}
}
scanf("%d%d",&beg,&endd);
dijikstra();
printf("%d %d\n",min_dist,min_cost);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: