题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=3790
最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 26741 Accepted Submission(s): 7937
Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
(1<n<=1000, 0<m<100000, s != t)
Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
Sample Output
9 11
Dijkstra算法。在跑Dijkstra的过程中使用一个cost数组记录最小花费。
花费要在满足路径最短的前提下保持最短,应这样处理:
(核心代码)
if(dis[j]>dis[mark]+g[mark][j])
{
dis[j]=dis[mark]+g[mark][j];
cost[j]=cost[mark]+t[mark][j];
}
else if(dis[j]==dis[mark]+g[mark][j])
{
cost[j]=min(cost[mark]+t[mark][j],cost[j]);
}
在Dijkstra算法更新最短路数值时更新cost数组。
代码:
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int g[1001][1010];
int t[1001][1010];
bool vis[1001];
int dis[1001],cost[1001];
const int inf=1e8+10;
int main()
{
ios::sync_with_stdio(false);
int n,m;cin>>n>>m;
while(n)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
g[i][j]=i==j?0:inf;
t[i][j]=i==j?0:inf;
}
}
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)dis[i]=inf;
for(int i=1;i<=m;i++)
{
int a,b,d,q;
cin>>a>>b>>d>>q;
if(d<g[a][b])
{
g[a][b]=g[b][a]=d;
t[a][b]=t[b][a]=q;
}
}
int s,e;
cin>>s>>e;
dis[s]=0;
cost[s]=0;
for(int i=1;i<=n;i++)
{
int mark=-1,tot=inf;
for(int j=1;j<=n;j++)
{
if(vis[j]==0&&tot>dis[j])
{
mark=j;
tot=dis[j];
}
}
vis[mark]=1;
for(int j=1;j<=n;j++)
{
if(vis[j]==0)
{
if(dis[j]>dis[mark]+g[mark][j])
{
dis[j]=dis[mark]+g[mark][j];
cost[j]=cost[mark]+t[mark][j];
}
else if(dis[j]==dis[mark]+g[mark][j])
{
cost[j]=min(cost[mark]+t[mark][j],cost[j]);
}
}
}
}
cout<<dis[e]<<" "<<cost[e]<<endl;
cin>>n>>m;
}
return 0;
}