https://leetcode-cn.com/problems/DFPeFJ/

分析

#define P pair<int, int>
#define PP pair<int,P> //时间 城市 电量
class Solution {
public:
    //f[i][j]表示从start到i城市且有j单位电量所要花费的最少时间
    //f[i][j]=f[i][k]+(j-k)*charge[i]
    //f[i'][j-d]=f[i][j]+d,其中i'是能够走到的下一个城市,j>=d,d是i和i’之间的距离
    int f[105][105]={0},D[105][105]={0},INF=0x3fffffff;
    void dijkstra(int start,int cnt,int n,vector<int> & charge)
    {
        priority_queue<PP,vector<PP>,greater<PP>> Q;
        f[start][0]=0;
        Q.push(PP(0,P(start,0)));
        while(!Q.empty())
        {
            PP tmp=Q.top();Q.pop();
            int time=tmp.first,city=tmp.second.first,ele=tmp.second.second;
            if(time>f[city][ele])continue;
            for(int lc=0;lc+ele<=cnt;lc++)
            {
                //走到f[city][lc+ele]
                if(f[city][lc+ele]>time+lc*charge[city])
                {
                    f[city][lc+ele]=time+lc*charge[city];
                    Q.push(PP(time+lc*charge[city],P(city,ele+lc)));
                }
            }
            //走到f[city'][ele-d]
            for(int i=0;i<n;i++)
            {
                if(D[city][i]&&D[city][i]<=ele)
                {
                    if(f[i][ele-D[city][i]]>time+D[city][i])
                    {
                        f[i][ele-D[city][i]]=time+D[city][i];
                        Q.push(PP(time+D[city][i],P(i,ele-D[city][i])));
                    }
                }
            }
        }
    }
    int electricCarPlan(vector<vector<int>>& paths, int cnt, int start, int end, vector<int>& charge){
        int n=charge.size();
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<=cnt;j++)f[i][j]=INF;
        }
        for(auto x:paths)
        {
            if(!D[x[0]][x[1]])D[x[0]][x[1]]=x[2],D[x[1]][x[0]]=x[2];
            else D[x[0]][x[1]]=min(D[x[0]][x[1]],x[2]),D[x[1]][x[0]]=min(D[x[1]][x[0]],x[2]);
        }
        dijkstra(start,cnt,n,charge);
        int ans=INF;
        for(int i=0;i<=cnt;i++)
        {
            if(f[end][i]<ans)ans=f[end][i];
        }
        return ans;
    }
};