LeetCode 1928. 规定时间内到达终点的最小花费

LeetCode 1928. 规定时间内到达终点的最小花费
在这里插入图片描述

二维最短路

typedef pair<int, int> PII;
#define x first
#define y second
const int N = 1010, M = 2010, INF = 0x3f3f3f3f;
class Solution {
public:
    int h[N], w[M], e[M], ne[M], idx = 0;
    int dist[N][N]; //起点到i,花费时间为j的最小通行费用
    bool st[N][N] = {false};
    void add(int a, int b, int c)
    {
        e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
    }
    void spfa(int m, vector<int>& pf)
    {
        memset(dist, 0x3f, sizeof dist);
        queue<PII> q;
        q.push({0, 0});
        dist[0][0] = pf[0];
        st[0][0] = true;
        while(!q.empty())
        {
            auto t = q.front();
            q.pop();
            st[t.x][t.y] = false;
            for(int i = h[t.x]; ~i; i = ne[i])
            {
                int x = e[i], y = t.y + w[i];
                if(y > m) continue;
                if(dist[x][y] > dist[t.x][t.y] + pf[x])
                {
                    dist[x][y] = dist[t.x][t.y] + pf[x];
                    if(!st[x][y])
                    {
                        q.push({x, y});
                        st[x][y] = true;
                    }
                }
            }
        }
    }
    int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& pf) {
        memset(h, -1, sizeof h);
        for(auto&& e : edges)
        {
            int a = e[0], b = e[1], c = e[2];
            add(a, b, c), add(b, a, c);
        }
        spfa(maxTime, pf);
        int n = pf.size();
        int res = INF;
        for(int i = 0; i <= maxTime; i ++)
        {
            res = min(res, dist[n - 1][i]);
        }
        if(res == INF) return -1;
        else return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值