最短路径问题
题目描述:
给你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)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0
样例输出:
9 11
code
#include<iostream>
#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 (cin >> n >> m && n > 0 && m > 0)
{
//初始化邻接链表
for (int i = 1; i <= n; i++)
edge[i].clear();
//输入
while (m--)
{
int a, b, c, cost;
cin >> 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);
}
//起点终点初始化
cin >> S >> T;
for (int i = 1; i <= n; i++)
{
Dis[i] = -1;
mark[i] = false;
}
Dis[S] = 0;
mark[S] = true;
int newP = S; //起点为S,加入集合K
for (int i = 1; i < n; i++)
{
for (size_t 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[t] > 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;
}
cout << Dis[T] << " " << cost[T] << endl;
}
return 0;
}