最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 20086 Accepted Submission(s): 5971
点击打开链接
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
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#define min(a, b) (a < b) ? a: b
#define MAX_N 1005
using namespace std;
const int INF = 9999999;
bool used[MAX_N];
int cost[MAX_N][MAX_N];
int d[MAX_N];
int mincost[MAX_N];
int dis[MAX_N][MAX_N];
int main()
{
int n, m, a, b, cos, s, t, disrt;
while (scanf("%d %d", &n, &m), n && m)
{
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= n; j++) {
if(i == j){
dis[i][j] = dis[i][j] = 0;
cost[i][j] = cost [j][i] = 0;
}
else dis[j][i] = dis[i][j] = cost[i][j] = cost[j][i] = INF;
}
}
for (int i = 1; i <= m; i++) {
scanf("%d %d %d %d", &a, &b, &disrt, &cos);
if(dis[a][b] > disrt) {
dis[a][b] = dis[b][a] = disrt;
cost[a][b] = cost[b][a] = cos;
} else if (dis[a][b] == disrt) {
cost[a][b] = cost[b][a] = min(cost[a][b], cos);
}
}
scanf("%d %d", &s, &t);
memset(d,INF,sizeof(d));
memset(used,false,sizeof(used));
memset(mincost,INF,sizeof(mincost));
d[s] = 0;
mincost[s] = 0;
while (true) {
int v = -1;
for (int u = 1; u <= n; u++) {
if(!used[u]&&(v == -1 || d[v] > d[u])) v = u;
}
if (v == -1) break;
used[v] = true;
for (int u = 1; u <= n; u++) {
if (d[u] > d[v] + dis[u][v]) {
d[u] = d[v] + dis[u][v];
mincost[u] = cost[v][u] + mincost [v];
} else if (d[u] == d[v] + dis[u][v]) {
mincost[u] = min(mincost[u], mincost[v] + cost[u][v]);
}
}
}
printf("%d %d\n", d[t], mincost[t]);
}
return 0;
}
对于数据的初始话,我就呵呵了,一直WA了十多遍,看别人的代码才改过来。。。。。