王道机试练习——最短路径最短花费
题目描述
给你 n 个点, m 条无向边,每条边都有长度 d 和花费 p,给你起点 s 终点 t, 要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花 费最少的。
输入: 输入 n,m,点的编号是 1~n,然后是 m 行,每行 4 个数 a,b,d,p,表示 a 和 b 之间有一条边,且其长度为 d,花费为 p。最后一行是两个数 s,t;起点 s,终点 t。 n 和 m 为 0 时输入结束。 (1<n<=1000, 0<m<100000, s != t)
输出: 输出 一行有两个数, 最短距离及其花费。
代码
#include<stdio.h>
#include<vector>
using namespace std;
struct E {//邻接链表结构体
int next;
int c;
int cost;
};
vector<E>edge[1001];
int Dis[1001];//距离数组
int cost[1001];//花费数组
bool mark[1001];//是否属于集合K数组
int main() {
int n, m;
int S, T;//起点终点
while (scanf("%d%d", &n, &m) != EOF) {
if (n == 0 && m == 0) break;
for (int i = 1; i <= n; i++) edge[i].clear();
while (m--) {
int a, b, c, cost;
scanf("%d%d%d%d", &a, &b, &c, &cost);
E tmp;
tmp.c = c;
tmp.cost = cost;
tmp.next = b;
edge[a].push_back(tmp);
tmp.next = a;
edge[b].push_back(tmp);
}
scanf("%d%d", &S, &T);//输入起点终点
for (int i = 1; i <= n; i++) {
Dis[i] = -1;
mark[i] = false;
}
Dis[S] = 0;
mark[S] = true;
int newP = S;
for (int i = 1; i < n; i++) {
for (int j = 0; j < edge[newP].size(); j++) {
int t = edge[newP][j].next;
int c = edge[newP][j].c;
int co = edge[newP][j].cost;
if (mark[t] == true) continue;
if (Dis[t] == -1 || Dis[t] > Dis[newP] + c || Dis[t] == Dis[newP] + c && cost[c] > cost[newP] + co) {
Dis[t] = Dis[newP] + c;
cost[t] = cost[newP] + co;
}
}
int min = 123123123;
for (int j = 1; j <= n; j++) {
if (mark[j] == true) continue;
if (Dis[j] == -1) continue;
if (Dis[j] < min) {
min = Dis[j];
newP = j;
}
}
mark[newP] = true;
}
printf("%d%d\n", Dis[T], cost[T]);
}
return 0;
}
本文介绍了一个解决特定图论问题的算法实现:在带有长度和花费属性的无向图中找到从起点到终点的最短路径及最小花费。通过使用邻接链表结构和迭代改进距离与花费的方法,确保了算法的高效性和准确性。
653

被折叠的 条评论
为什么被折叠?



