您的位置:首页 > 编程语言 > PHP开发

SRM675 medium ShortestPathWithMagic(DP+Dijkstra)

2015-12-18 10:00 232 查看
题意: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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: