有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
题解
用 Dijkstra 最后一个点过不去,没找出来哪里有问题,先咕着。用 Floyd 做
#include <bits/stdc++.h>
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
int n, m, s, d;
int a[501][501];
int c[501][501];
cin >> n >> m >> s >> d;
for (int i = 0; i <= n; ++i)
{
for (int j = 0; j <= n; ++j)
{
if (i == j)
{
a[i][j] = c[i][j] = 0;
}
else
{
a[i][j] = c[i][j] = INT16_MAX;
}
}
}
while (m--)
{
int i, j, d, cost;
cin >> i >> j >> d >> cost;
a[i][j] = a[j][i] = d;
c[i][j] = c[j][i] = cost;
}
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (i != j && i != k && j != k)
if (a[i][j] > a[i][k] + a[k][j] || (a[i][j] == a[i][k] + a[k][j] && c[i][j] > c[i][k] + c[k][j]))
{
a[i][j] = a[i][k] + a[k][j];
c[i][j] = c[i][k] + c[k][j];
}
cout << a[s][d] << " " << c[s][d] << endl;
return 0;
}
最后一个点过不去的 Dijkstra
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int distance;
int cost;
};
int cost = 0;
int dij(Node a[501][501], int n, int b, int e)
{
bool visited[n];
int distance[n];
int c[n];
for (int i = 0; i <= n; ++i)
{
visited[i] = false;
c[i] = INT16_MAX;
distance[i] = INT16_MAX;
}
visited[b] = true;
distance[b] = 0;
c[b] = 0;
int cur = b;
int nextPoint = -1;
int times = 0;
while (cur != e && times < (n - 1))
{
int minL = INT16_MAX;
for (int j = 0; j < n; ++j)
{
if (visited[j])
continue;
if (distance[j] > distance[cur] + a[cur][j].distance ||(distance[j] == distance[cur] + a[cur][j].distance && c[j] > c[cur]+a[cur][j].cost))
{
distance[j] = distance[cur] + a[cur][j].distance;
c[j] = c[cur] + a[cur][j].cost;
}
if (distance[j] < minL)
{
minL = j;
nextPoint = j;
}
}
visited[nextPoint] = true;
cur = nextPoint;
times++;
}
cost = c[e];
return distance[e];
}
int main()
{
std::ios::sync_with_stdio(false);
int n, m, s, d;
cin >> n >> m >> s >> d;
Node a[501][501];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j <= n; ++j)
{
if (i == j)
a[i][j].distance = 0;
else
a[i][j].distance = INT16_MAX;
}
}
while(m--)
{
int i,j,distance,cost;
cin>>i>>j>>distance>>cost;
a[i][j].distance = a[j][i].distance = distance;
a[i][j].cost = a[j][i].cost = cost;
}
int ans = dij(a,n,s,d);
cout<<ans<<" "<<cost<<endl;
return 0;
}