Jobdu 题目1008:最短路径问题

http://ac.jobdu.com/problem.php?pid=1008

题目描述:
给你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
#include <cstdio>
#include <vector>
using namespace std;
struct E{
	int next;
	int d, p;
};
vector<E> edge[100000];
int Dis[1001], Pri[1001];
bool mark[1001];
int main(){
	int n, m;
	while (scanf("%d%d", &n, &m) != EOF && !(n == 0 && m == 0)){
		for (int i = 1; i <= n; i++){
			edge[i].clear();
			Dis[i] = -1;
			mark[i] = false;
		}
		while (m--){
			int a, b, d, p;
			scanf("%d%d%d%d", &a, &b, &d, &p);
			E tmp;
			tmp.d = d;
			tmp.p = p;
			tmp.next = b;
			edge[a].push_back(tmp);
			tmp.next = a;
			edge[b].push_back(tmp);
		}
		int s, t;
		scanf("%d%d", &s, &t);
		Dis[s] = 0;
		Pri[s] = 0;
		mark[s] = true;
		int newP = s;
		for (int i = 0; i < n; i++){
			for (int j = 0; j < edge[newP].size(); j++){
				int t = edge[newP][j].next;
				int d = edge[newP][j].d;
				int p = edge[newP][j].p;
				if (mark[t] == true) continue;
				if (Dis[t] == -1 || Dis[t] > Dis[newP] + d){
					Dis[t] = Dis[newP] + d;
					Pri[t] = Pri[newP] + p;
				}
				else if (Dis[t] == Dis[newP] + d){
					if (Pri[t] > Pri[newP] + p){
						Dis[t] = Dis[newP] + d;
						Pri[t] = Pri[newP] + p;
					}
				}
			}
			int min = 1999999999;
			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], Pri[t]);
	}
	return 0;
} 


你可能感兴趣的:(Jobdu 题目1008:最短路径问题)