poj 1724 roads 图论

poj 1724
题目大意:N个城市,编号1到N。城市间有R条单向道路。
每条道路连接两个城市,有长度和过路费两个属性。
Bob只有K块钱,他想从城市1走到城市N。求在钱够花的情况下的最短路。如果到不了N,输出-1

思路:dijkstra以长度排序,每次松弛的时候判断钱用完没有,如果没有:松弛;如果用完了则不进行松弛。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int maxn = 100 + 2;
int head[maxn],vis[maxn],k = 1,n,r,cost;
struct edge
{
    int v,w,next,len;//len表示路的长度,w表示过路费
}e[maxn * maxn];
struct node
{
    int now,dis,co;
    bool operator < (const node &a) const//以长度排序
    {
        if(dis != a.dis) return dis > a.dis;
        return co > a.co;
    }
};
void adds(int u,int v,int len,int w)
{
    e[k].v = v;
    e[k].w = w;
    e[k].len = len;
    e[k].next = head[u];
    head[u] = k++;
}
priority_queue <node> q;
void dijkstra()
{
    node st;
    st.dis = 0;
    st.co = 0;
    st.now =  1;
    q.push(st);
    while(!q.empty())
    {
        node no = q.top();
        int u = no.now;
        q.pop();
        if(u == n)
        {
            printf("%d",no.dis);
            return;
        }
        for(int i = head[u]; i != -1; i = e[i].next)
        {
            int v = e[i].v;
            if(no.co + e[i].w <= cost)//判断钱是否用完
            {
                node cs;
                cs.now = v;
                cs.dis = no.dis + e[i].len;
                cs.co = no.co + e[i].w;
                q.push(cs);
            }
        }
    }
    printf("-1");
}
int main()
{
    int a,b,c,d;
    scanf("%d%d%d",&cost,&n,&r);
    memset(head,-1,sizeof(head));
    for(int i = 1; i <= r; ++i)
    {
        scanf("%d%d%d%d",&a,&b,&c,&d);
        adds(a,b,c,d);
    }
    dijkstra();
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值