SRM675 medium ShortestPathWithMagic(DP+Dijkstra)

来源:互联网 发布:日本福岛核事故知乎 编辑:程序博客网 时间:2024/05/13 08:56

题意: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
原创粉丝点击