最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 44472 Accepted Submission(s): 12760
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)
Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2
1 2 5 6
2 3 4 5
1 3
0 0
Sample Output
9 11
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3790
solution:我觉得SPFA算法像个广搜。。。
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
struct node{
int len, cost;
}graph[1005][1005];
node dis[1005];
int m, n;
bool vis[1005];
void spfa(int x){
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; ++i){
dis[i].len = dis[i].cost = INF;
}
dis[x].len = dis[x].cost = 0;
queue<int> q;
q.push(x);
vis[x] = true;
while (!q.empty()){
int temp = q.front();
q.pop();
vis[temp] = false;
for (int i = 1; i <= n; ++i){
if (graph[temp][i].len + dis[temp].len < dis[i].len && graph[temp][i].len != INF){
dis[i].len = graph[temp][i].len + dis[temp].len;
dis[i].cost = graph[temp][i].cost + dis[temp].cost;
if (!vis[i]){
q.push(i);
vis[i] = true;
}
}
if (graph[temp][i].len + dis[temp].len == dis[i].len && graph[temp][i].cost + dis[temp].cost < dis[i].cost){
dis[i].cost = graph[temp][i].cost + dis[temp].cost;
}
}
}
}
int main()
{
while (cin >> n >> m){
if (!n && !m)return 0;
for (int i = 1; i <= n; ++i){
for (int j = 1; j <= n; ++j){
if (i == j)graph[i][j].len = graph[i][j].cost = 0;
else graph[i][j].len = graph[i][j].cost = INF;
}
}
int s, e, d, p;
for (int i = 1; i <= m; ++i){
scanf("%d%d%d%d", &s, &e, &d, &p);
if (d < graph[s][e].len){
graph[s][e].len = graph[e][s].len = d;
graph[s][e].cost = graph[e][s].cost = p;
}else if (d == graph[s][e].len && p < graph[s][e].cost){
graph[s][e].cost = graph[e][s].cost = p;
}
}
int st, ed;
scanf("%d%d", &st, &ed);
spfa(st);
printf("%d %d\n", dis[ed].len, dis[ed].cost);
}
}