SRM675 medium ShortestPathWithMagic(DP+Dijkstra)

题意:n个完全图,找出0到1的最短路,其中有k个魔法可以使用,每使用一个,当前道路的长度就会变为原来的一半。

分析:设每个点有k中状态,更新每一个状态的最小值。

代码:

#include <bits/stdc++.h>
#include <queue>
#include <string>
#define LL long long
#define FOR(i,x,y)  for(int i = x;i < y;++ i)
#define IFOR(i,x,y) for(int i = x;i > y;-- i)

using namespace std;

const int maxn = 55;
const double inf = 1<<30;

typedef pair<int,int>   pii;

struct Node{
    double val;
    int id,w;
    Node()  {}
    Node(double a,int b,int c)  : val(a),id(b),w(c){}
    bool operator < (const Node& rhs) const{
        if(val == rhs.val)  return w > rhs.w;
        return val > rhs.val;       
    }
};

double dp[maxn][maxn];
bool vis[maxn][maxn];

class  ShortestPathWithMagic{
    public :
        double getTime(vector <string> dist, int k){
            int n = dist.size();
            memset(vis,false,sizeof(vis));
            priority_queue<Node> q;
            FOR(i,0,maxn) FOR(j,0,maxn) dp[i][j] = inf;
            dp[0][0] = 0;
            q.push(Node(dp[0][0],0,0));
            while(!q.empty()){
                Node u = q.top(); q.pop();
                int id = u.id,w = u.w;
                if(vis[id][w]) continue;
                vis[id][w] = true;
                //printf("%f %d %d\n",dp[id][w],id,w);
                FOR(i,0,n){
                    if(i == id) continue;   
                    if(dp[i][w] > dp[id][w]+dist[i][id]-'0'){
                        dp[i][w] = dp[id][w]+dist[i][id]-'0';
                        //printf("%f %d %d\n",dp[i][w],i,w);
                        q.push(Node(dp[i][w],i,w));
                    }
                    if(w+1 <= k && dp[i][w+1] > dp[id][w]+(dist[i][id]-'0')/2.0){
                        dp[i][w+1] = dp[id][w]+(dist[i][id]-'0')/2.0;
                        //printf("%f %d %d\n",dp[i][w+1],i,w+1);
                        q.push(Node(dp[i][w+1],i,w+1));
                    }
                }
                //printf("\n\n");
            }   
            double ans = inf;
            FOR(i,0,k+1)    ans = min(dp[1][i],ans);
            return ans;
        }
}res;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值