九度 OJ 题目1008:最短路径问题 (Dijstra 算法)

题目描述:
给你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

该题与 九度OJ题目1447:最短路 使用相同思想,只是多了一个cost变量

九度OJ题目1447:最短路 我的解法:http://blog.csdn.net/qq_31820885/article/details/61925864

#include <stdio.h>
#include<vector>
using namespace std;

struct E{
    int next;
    int weight;
    int cost;
};
vector<E> edge[1001];
bool mark[1001];
int dis[1001];
int costs[1001];


int main()
{
    int n,m;
    while(scanf("%d%d", &n,&m)!=EOF) {
        if(n == 0 && m == 0) break;
        for(int i=1;i<=n;i++) edge[i].clear();      //初始化
        int p1,p2,weight,cost;
        //录入
        while(m--) {
            scanf("%d%d%d%d",&p1,&p2,&weight,&cost);
            E tmp;
            tmp.weight = weight;
            tmp.cost = cost;
            tmp.next = p1;
            edge[p2].push_back(tmp);    //p2与p1的连线放到p2的vector中
            tmp.next = p2;
            edge[p1].push_back(tmp);    //该图是无向图,所有要两个节点的vector都要存彼此
        }
        int s,t;
        scanf("%d%d", &s,&t);
        //初始化
        for(int i=1;i<=n;i++) {
            mark[i] = false;
            dis[i] = -1;
   //         costs[i] = 0;
        }
        //从s节点为初始K集合
        mark[s] = true;
        dis[s] = 0;
        int newP = s;   //新加入K集合的节点
        //循环找到特定节点到其他n-1个节点的最短路径
        for(int i=1;i<n;i++) {
            for(int j=0;j<edge[newP].size();j++) {
                int next = edge[newP][j].next;  //新加入节点的相邻节点
                int weight = edge[newP][j].weight;
                int cost = edge[newP][j].cost;
                if(mark[next] == true) continue;        //若next节点已经是集合K的成员
                //(dis[next]==dis[newP]+c) && (costs[next]>costs[newP]+cost)该句体现距离相等时取花费少的
                if(dis[next] == -1 || dis[next] > dis[newP] + weight ||
                   ((dis[next] == dis[newP] + weight) && (costs[next] > costs[newP] + cost))) {
                    dis[next] = dis[newP] + weight;     //更新距离
                    costs[next] = costs[newP] + cost;   //更新花费
                }
            }

            int min = 9999999;
            //循环查找K集合与U集合之间已经计算出dis值得边的最小边,另其为新加入点
            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;      //将新加入点列入K集合
        }
        printf("%d %d\n", dis[t], costs[t]);
    }
    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值