题目1008:最短路径问题

来源:互联网 发布:淘宝助理怎么修改标题 编辑:程序博客网 时间:2024/05/29 08:30
/****************************************题目描述:给你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 21 2 5 62 3 4 51 30 0样例输出:9 11*********************************************************/#include <iostream>#include <cstring>#include <fstream>#include <algorithm>using namespace std;const int N = 1000 + 10;const int M = 100000 + 10;const int INF = 100000000;int n, m;int s, t;int f[N][N];int cost[N][N];bool vis[N];int d[N], c[N];void dijstra();int main(){#ifndef ONLINE_JUDGE    ifstream cin("d:\\OJ\\uva_in.txt");#endif // ONLINE_JUDGE    while (cin >> n >> m) {        if (n == 0 && m == 0)            break;        fill(&f[0][0], &f[N][0], INF);        fill(&cost[0][0], &cost[N][0], INF);        while (m--) {            int u, v;            cin >> u >> v;            cin >> f[u][v] >> cost[u][v];            f[v][u] = f[u][v];            cost[v][u] = cost[u][v];        }        cin >> s >> t;        dijstra();        cout << d[t] << " " << c[t] << endl;    }    return 0;}void dijstra(){    int x;    fill(vis, vis + n, false);    for (int i = 1; i <= n; i++) {        d[i] = (i == s) ? 0 : INF;        c[i] = (i == s) ? 0 : INF;    }    for (int i = 1; i <= n; i++) {        int min = INF;        for (int j = 1; j <= n; j++) {            if (!vis[j] && d[j] < min) {                min = d[j];                x = j;            }        }        //cout << "x:" << x << endl;        vis[x] = 1;        for (int j = 1; j <= n; j++) {            if (d[j] > d[x] + f[x][j])                d[j] = d[x] + f[x][j];            //cout << "d[j]:" << d[j] << endl;            if (c[j] > c[x] + cost[x][j])                c[j] = c[x] + cost[x][j];            //cout << "c[j]:" << c[j] << endl;        }    }}

原创粉丝点击