九度OJ——1008最短路径问题

来源:互联网 发布:辣酱油 知乎 编辑:程序博客网 时间:2024/06/05 19:52

题目描述:
给你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时输入结束。
(n>1,n<=1000,m>0, m<100000, s != t)
输出:
输出 一行有两个数, 最短距离及其花费。
样例输入:
3 2
1 2 5 6
2 3 4 5
1 3
0 0
样例输出:
9 11


思路:Dijiskstra算法的应用,这里不止要判断路径长度,同时也要判断花费。(奇怪的是,九度OJ上提交显示错误,在牛客网上提交却是正确的,真的不想在吐槽了九度OJ,真的很菜)
AC代码:

#include <iostream>#include <cmath>using namespace std;const int MAX = 65535;int Dist[1001][1001],Cost[1001][1001];int N,M;int dist[1001],cost[1001],collected[1001];int FindMinVertex(){    int MinDist = 65535,MinV = 0;    for(int i = 1 ; i < N+1 ; i++){        if(collected[i] == 0 && dist[i] < MinDist){            MinDist = dist[i];            MinV = i;        }    }    if(MinDist < MAX){        return MinV;    }else{        return -1;    }}void Dijikstra(int start){    for(int i = 1 ; i < N+1 ; i++){        dist[i] = Dist[start][i];        cost[i] = Cost[start][i];    }    dist[start] = 0;    collected[start] = 1;    cost[start] = 0;    while(1){        int v = FindMinVertex();    //找到未收录顶点中的最小者         if(v == -1){            break;        }        collected[v] = 1;        for(int i = 1 ; i < N+1 ; i++){            if(Dist[v][i] != MAX && Cost[v][i] != MAX &&                dist[v] + Dist[v][i] <= dist[i]){                if((dist[i] == dist[v] + Dist[v][i] && cost[i] > cost[v] +Cost[v][i])                    || dist[i] > dist[v] + Dist[v][i]){                        cost[i] = cost[v] + Cost[v][i];                }                dist[i] = dist[v] + Dist[v][i];            }        }    }}int main(){    while(cin>>N>>M){        if(N == 0 && M == 0){            break;        }        for(int i = 0 ; i < 1001 ; i++){            collected[i] = 0;            dist[i] = MAX;            cost[i] = MAX;            for(int j = 0 ; j < 1001 ; j++){                Dist[i][j] = Cost[i][j] = MAX;            }        }        int start,end,c,len;         for(int i = 0 ; i < M ; i++){            cin>>start>>end>>len>>c;            if(len < Dist[start][end]){                Dist[start][end] = Dist[end][start] = len;                Cost[start][end] = Cost[end][start] = c;                }else if(len == Dist[start][end] && c <Cost[start][end]){                Cost[start][end] = Cost[end][start] = c;            }         }        cin>>start>>end;        Dijikstra(start);        cout<<dist[end]<<" "<<cost[end]<<endl;    }    return 0;}
原创粉丝点击