POJ 1724 ROADS

Dijkstra算法求最短路径
本文介绍了一种结合Dijkstra算法与优先队列解决带有额外限制条件(如花费限制)的最短路径问题的方法。通过C++实现,具体展示了如何在图中找到从起点到终点花费不超过特定阈值k的最短路径。

题目链接

题意:找花费不超过k的最短路。

分析:dijkstra+优先队列+bfs

#include<cstdio>
#include<algorithm>
#include<vector>
#include<iostream>
#include<functional>
#include<cstring>
#include<queue>
#define MAX_V 105
#define inf 1000000000
using namespace std;
struct edge
{
    int to,cost,toll;
    edge(){}
    edge(int to,int cost,int toll):to(to),cost(cost),toll(toll){}
};
struct P
{
    int first;
    int second;
    int third;
    P(int first,int second,int third):first(first),second(second),third(third){}
    bool operator<(const P &other)const
    {
        return first>other.first;
    }
};
int V;
vector<edge>G[MAX_V];
int k,r;
int tol;
int dijkstra(int s)
{
    priority_queue<P>que;
    que.push(P(0,s,0));
    while(!que.empty())
    {
        P p=que.top();
        que.pop();
        int v=p.second;
        if(v==V)
        return p.first;
        for(int i=0;i<G[v].size();i++)
        {
            edge e=G[v][i];
            if(p.third+e.toll<=k)
            que.push(P(p.first+e.cost,e.to,p.third+e.toll));
        }
    }
    return -1;
}
int main(void)
{
    while(scanf("%d%d%d",&k,&V,&r)==3)
    {
        for(int i=0;i<r;i++)
        {
            int s,e,l,t;
            scanf("%d%d%d%d",&s,&e,&l,&t);
            G[s].push_back(edge(e,l,t));
//          G[e].push_back(edge(s,l,t));
        }
        tol=0;
        printf("%d\n",dijkstra(1));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值