1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
| #include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,k,n) for(int i=k;i<(int)(n);i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define INF 1<<30
#define mp make_pair
#define EPS 1e-4
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<double, int> D;
int h, w;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
bool can(int y, int x) {
if(0 <= y && y < h && 0 <= x && x < w) return true;
return false;
}
struct edge {
int from,to;
int cost;
edge(int t,int c) : to(t),cost(c) {}
edge(int f,int t,int c) : from(f),to(t),cost(c) {}
bool operator<(const edge &e) const {
return cost < e.cost;
}
};
int d[100005];
vector<edge> G[10005];
void dijkstra(int s, int n) {
priority_queue<P, vector<P>, greater<P> > que;
rep(i, n) {
d[i] = INF;
}
d[s] = 0;
que.push(P(0,s));
while(que.size()) {
P p = que.top();
que.pop();
int v = p.second;
if(d[v] < p.first) continue;
rep(i, G[v].size()) {
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to],e.to));
}
}
}
}
class ExpensiveTravel {
public:
int minTime(vector <string> m, int startRow, int startCol, int endRow, int endCol) {
h = m.size(), w = m[0].size();
int n = h * w;
double v[55][55];
memset(v, 0, sizeof(v));
rep(i, h) {
rep(j, w) {
int t = (m[i][j] - '0');
v[i][j] = t;
}
}
double cost[2505];
rep(i, n) {
G[i].clear();
}
rep(i, h) {
rep(j, w) {
rep(k, n) cost[k] = INF;
cost[i*w+j] = 0;
priority_queue<D, vector<D>, greater<D> > que;
que.push(mp(1.0 / v[i][j], i * w + j));
while(que.size()) {
D di = que.top(); que.pop();
int y = di.second / w;
int x = di.second % w;
rep(k, 4) {
int ny = y + dy[k];
int nx = x + dx[k];
if(can(ny, nx) && cost[ny*w+nx] > di.first + 1.0 / v[ny][nx]) {
cost[ny*w+nx] = di.first + 1.0 / v[ny][nx];
if(cost[ny*w+nx] < 1.0 + EPS) {
que.push(mp(cost[ny*w+nx], ny * w + nx));
G[i*w+j].push_back(edge(ny*w+nx, 1));
}
}
}
}
}
}
startRow--;
startCol--;
dijkstra(startRow * w + startCol, n);
endRow--;
endCol--;
if(d[endRow * w + endCol] == INF) {
return -1;
}
return d[endRow * w + endCol];
}
};
|