最短路径问题
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 29132 Accepted Submission(s): 8661
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
Source
Recommend
notonlysuccess | We have carefully selected several similar problems for you:
1217
1142
1548
1385
1598
很裸的单源最短路,双权值判断其实就是多出一个条件判断语句而已。。。
数据预处理很重要。。。。
#include <iostream>
#include <cmath>
#include <algorithm>
#include <ctime>
using namespace std;
const int maxn = 1005;
const int inf = 1<<25;
int n,m,d,p,a,b,s,t;
int MAP[maxn][maxn],cost[maxn][maxn];
int dist[maxn],c[maxn];
bool used[maxn];
void dijstra(){
for (int i=1; i<=n; i++) {
dist[i] = inf;
c[i] = inf;
used[i] = 0;
}
dist[s] =0; used[s] = 1 ; c[s] = 0;
int tmp = s;
for (int i=1; i<=n; i++) {
for (int k=1; k<=n; k++) {
if (dist[k] > dist[tmp] + MAP[tmp][k]) {
dist[k] = dist[tmp] + MAP[tmp][k];
c[k] = c[tmp] + cost[tmp][k];
}
else if (dist[k] == dist[tmp] + MAP[tmp][k]){
c[k] = min(c[k], c[tmp] + cost[tmp][k]);
}
}
int mindist = inf;
for (int k=1; k<=n; k++) {
if (!used[k] && dist[k] < mindist) {
mindist = dist[k];
tmp = k;
}
}
used[tmp] = 1;
}
}
int main(){
int i,j,k;
std::ios::sync_with_stdio(false);
while (cin >> n >> m && n+m) {
for (i=1; i<=n; i++) {
for (j=1; j<=n; j++)
MAP[i][j] = inf;
cost[i][j] = inf;
}
for (i=1; i<=m; i++) {
cin >> a >> b >> d >> p;
if ((MAP[a][b] > d) || (MAP[a][b] == d && cost[a][b] > p)) { //这个判断很重要,没有之前一直WA
MAP[b][a] = MAP[a][b] = d;
cost[a][b] = cost[b][a] = p;
}
}
cin >> s >> t;
dijstra();
cout << dist[t] << " " << c[t] << endl;
}
return 0;
}