算法题 最短路径-04-最短路径问题

给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点t。n和m为0时输入结束。
(1 Output
输出 一行有两个数, 最短距离及其花费。
Sample Input
3 2
1 2 5 6
2 3 4 5
1 3
0 0
Sample Output
9 11

思路:模板题,dijkstra算法变下行即可。

#include
#include
#include
using namespace std;
#define INF 99999999
#define MM 1005
int a[MM][MM], dis[MM], book[MM],time[MM][MM],dtime[MM];
int n, t, t1, t2, t3, min1, flag,times, star,end1;
int main()
{
	while (scanf("%d%d", &n, &t) != EOF) {
		if (t == 0 && n == 0) {
			break;
		}
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				if (i == j)
				{
					a[i][j] = 0;
					time[i][j] = 0;
				}
				else {
					a[i][j] = INF;
					time[i][j] = INF;
				}
				for (int i = 0; i t3) {
						a[t1][t2] = a[t2][t1] = t3;
						time[t1][t2] = time[t2][t1] = times;
					}
					if (a[t1][t2] == t3) {
						if (time[t1][t2] > times) {
							time[t1][t2] = time[t2][t1] = times;
						}
					}
						
						
				}
				scanf("%d %d", &star, &end1);
				memset(dis, 0, sizeof(dis));
				memset(dtime, 0, sizeof(dtime));
				for (int i = 1; i <= n; i++)
				{
					dis[i] = a[star][i];
					dtime[i] = time[star][i];
					book[i] = 0;
				}
				book[star] = 1;
				for (int i = 1; i <= n; i++)
				{
					min1 = INF;
					for (int j = 1; j <= n; j++)
					{
						if (book[j] == 0 && dis[j] dis[flag] + a[flag][v]) {
							dis[v] = dis[flag] + a[flag][v];
							dtime[v] = dtime[flag] + time[flag][v];
						}
						if (dis[v] == dis[flag] + a[flag][v]) {//路程一样远时,选择时间最短
							if (dtime[v] > dtime[flag] + time[flag][v]) {
								dtime[v] = dtime[flag] + time[flag][v];
							}
						}
					}
				}
				printf("%d %d\n", dis[end1],dtime[end1]);
				
	}
	return 0;
}

你可能感兴趣的:(算法,dijkstra,算法)