poj1724_ROADS(优先队列广搜)

本文介绍了一种基于优先队列的广度优先搜索算法来解决最短路径问题的方法。该算法适用于路径长度不等于实际距离的情况,通过使用优先队列确保每次扩展时选择的是当前最优路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//本质上是对所有1为起点的路径的穷举
//但是这个数字太大了,深度搜索很有可能超时
//所以使用广度优先搜索
//一般的广度搜索是选择步数最少者为优,然而这次要选择距离短为优
//所以使用了优先队列而非普通队列
//有一个要注意的:Notice that different roads may have the same source and destination cities.建立图时要注意哦

#include<iostream>
#include<queue>
#include<cstring>
using  namespace std;
const int maxn = 107;
bool M[maxn][maxn];
typedef struct cell
{
    int State[2];
}cell;
vector<cell> Map[maxn][maxn];

typedef struct node
{
    bool Vis[maxn];
    int last;
    int dis;
    int cost;
    bool operator < (const node &b) const {
        return dis>b.dis;
    }
}node;

int main()
{
    ios::sync_with_stdio(false);
    int k, n, r;
    cin >> k >> n >> r;
    for (int i = 0; i<r; i++)
    {
        int s, d;
        cell lc;
        cin >> s >> d;
        cin >>lc.State[0]>>lc.State[1];
        M[s][d] = 1;
        Map[s][d].push_back(lc);
    }
    //解题思路:
    //由于步数!=距离所以不能用普通的宽度优先搜索,应该用优先队列宽度搜索
    //在到达目的地时,在拓展过程中减掉所有超支的路径.最后到达的一定是
    //最短且符合要求的
    priority_queue<node> Q;
    node start;
    memset(start.Vis, 0, sizeof(start.Vis));
    start.dis = 0;
    start.Vis[1] = 1;
    start.last = 1;
    start.cost = 0;
    Q.push(start);
    int ans = -1;
    while (!Q.empty())
    {
        node tn = Q.top();
        Q.pop();
        if (tn.last == n&&tn.cost<=k)
        {
            ans = tn.dis;
            break;
        }
        for (int i = 1; i <= n; i++)
        {
            if (!tn.Vis[i] && M[tn.last][i])
            {
                for (int j = 0; j < Map[tn.last][i].size(); j++)
                {
                    if (tn.cost + Map[tn.last][i][j].State[1] <= k)
                    {
                        node nn = tn;
                        nn.Vis[i] = 1;
                        nn.last = i;
                        nn.dis += Map[tn.last][i][j].State[0];
                        nn.cost += Map[tn.last][i][j].State[1];
                        Q.push(nn);

                    }

                }
            }
        }

    }
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值