Poj·ROADS

初见安~这里是传送门:Poj P1724

Description

城市中有R条有向马路,n个马路连接点,通过每条马路都要花去一定费用。你现在在编号为1的连接点 
手里有k元钱,要去n号连接点的最短路径的长度是多少?途中经过道路的花费不能超过k。注意:两个 
马路连接点间可能有多条马路 

Input

第一行,k(0 <= K <= 10000) 
第二行,n(2 <= N <= 100) 
第三行,R(1 <= R <= 10000 
以下R行 
x y L t 从x到y的马路,长度L(1<=每条马路的长度<=100),花费t(0<=每条马路的费用<=100) 

Output

满足条件最短路长度 

Sample Input

5
6
7
1 2 2 3
2 4 3 3
3 4 2 4
1 3 4 1
4 6 2 1
3 5 2 0
5 4 3 2

Sample Output

11

Sol

ps:原题目还要考虑一下没有合法最短路径时输出-1的情况,这里就把题意直接简化为保证有解了……关于-1应该是用spfa做,要用到入队次数上界的判定。

这是一个很经典的二维最短路问题。所谓二维,就是两重限制。所以其实在求最短路的时候加入这个限制,每个节点也不用考虑是否重复放入队列,考虑开销是否合法,优先队列维护最短距离即可。【很无脑】毕竟n很小。

上代码了——

#include<iostream>
#include<queue>
#include<cstring>
#define maxn 105
#define maxm 10005
using namespace std;
int n, m, k;
int read()
{
    int x = 0, ch = getchar();
    while(!isdigit(ch)) ch = getchar();
    while(isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar();
    return x;
}
 
struct edge
{
    int to, len, w, nxt;
    edge() {}
    edge(int tt, int ll, int ww, int nn) {to = tt, len = ll, w = ww, nxt = nn;}
}e[maxm];
 
int head[maxn], kk = 0;
void add(int u, int v, int w1, int w2)
{
    e[kk] = edge(v, w1, w2, head[u]);
    head[u] = kk++;
}
 
struct node//数组存下最短路作为参考是会影响正解的,有可能最短路的方案开销过大,所以捆一起传送了
{
    int num, dis, cost;
    node() {}
    node(int nn, int dd, int cc) {num = nn, dis = dd, cost = cc;}
    bool operator < (const node &x) const {return x.dis < dis;}
};
 
int dis[maxn];
bool vis[maxn];
int dij()
{
    priority_queue<node> q;
    q.push(node(1, 0, 0));
    register int u, v;
    while(q.size())
    {
        node now = q.top(); q.pop(); u = now.num;
        if(u == n) return now.dis;//优先队列维护下第一次取出n就是最短路径了
        for(int i = head[u]; ~i; i = e[i].nxt)
        {
            v = e[i].to;
            if(now.cost + e[i].w <= k) 
                q.push(node(v, now.dis + e[i].len, now.cost + e[i].w));//保证开销
        }
    }
}
 
int main()
{
    memset(head, -1, sizeof head);
    k = read(), n = read(), m = read();
    register int u, v, w1, w2;
    for(int i = 1; i <= m; i++)
        u = read(), v = read(), w1 = read(), w2 = read(), add(u, v, w1, w2);
         
    printf("%d\n", dij());
    return 0;
}

迎评:)
——End——

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值