Skip to content

Commit b289047

Browse files
authored
Create 3387.Maximize-Amount-After-Two-Days-of-Conversions.cpp
1 parent 3660f90 commit b289047

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
unordered_map<string,int>name2idx;
3+
public:
4+
double maxAmount(string initialCurrency, vector<vector<string>>& pairs1, vector<double>& rates1, vector<vector<string>>& pairs2, vector<double>& rates2)
5+
{
6+
unordered_set<string>Set;
7+
for (auto pair: pairs1)
8+
{
9+
Set.insert(pair[0]);
10+
Set.insert(pair[1]);
11+
}
12+
for (auto pair: pairs2)
13+
{
14+
Set.insert(pair[0]);
15+
Set.insert(pair[1]);
16+
}
17+
int idx = 0;
18+
for (string s: Set)
19+
name2idx[s] = idx++;
20+
21+
22+
int n = name2idx.size();
23+
vector<vector<double>> dist1 = floyd(pairs1, rates1);
24+
vector<vector<double>> dist2 = floyd(pairs2, rates2);
25+
26+
int s = name2idx[initialCurrency];
27+
double ret = 1.0;
28+
for (int i=0; i<n; i++)
29+
ret = max(ret, 1.0*dist1[s][i]*dist2[i][s]);
30+
return ret;
31+
}
32+
33+
vector<vector<double>> floyd(vector<vector<string>>& pairs, vector<double>& rates)
34+
{
35+
int n = name2idx.size();
36+
vector<vector<double>>dist(n, vector<double>(n,0));
37+
for (int i=0; i<n; i++)
38+
dist[i][i] = 1.0;
39+
for (int i=0; i<rates.size(); i++)
40+
{
41+
int a = name2idx[pairs[i][0]];
42+
int b = name2idx[pairs[i][1]];
43+
double t = rates[i];
44+
45+
for (int i=0; i<n; i++)
46+
for (int j=0; j<n; j++)
47+
{
48+
dist[i][j] = max(dist[i][j], dist[i][a]*t*dist[b][j]);
49+
dist[i][j] = max(dist[i][j], dist[i][b]*1.0/t*dist[a][j]);
50+
51+
dist[j][i] = max(dist[j][i], dist[j][a]*t*dist[b][i]);
52+
dist[j][i] = max(dist[j][i], dist[j][b]*1.0/t*dist[b][i]);
53+
}
54+
}
55+
return dist;
56+
}
57+
58+
59+
};

0 commit comments

Comments
 (0)