-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunit_converter.cc
More file actions
77 lines (63 loc) · 1.92 KB
/
Copy pathunit_converter.cc
File metadata and controls
77 lines (63 loc) · 1.92 KB
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
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
typedef std::pair<std::string, double> edge_t;
typedef std::map<std::string, std::vector<edge_t>> graph_t;
struct fact {
std::string unit_from_, unit_to_;
double ratio_; // unit_from * ration = unit_to
fact(std::string unit_from, std::string unit_to, double ratio)
: unit_from_(unit_from), unit_to_(unit_to), ratio_(ratio) {}
};
double coefficient(graph_t& g, const std::string& from, const std::string& to, std::set<std::string>& visited) {
if (visited.contains(from) || !g.contains(from)) {
return 0;
}
visited.insert(from);
if (from == to) {
return 1;
}
for (const edge_t& e : g[from]) {
double c = e.second * coefficient(g, e.first, to, visited);
if (c != 0) {
return c;
}
}
return 0;
}
int main() {
std::vector<fact> facts = {fact("m", "cm", 100), fact("m", "mm", 1000),
fact("h", "min", 60)};
graph_t graph;
for (const fact& f : facts) {
std::pair<std::string, double> edge = {f.unit_to_, f.ratio_};
if (graph.contains(f.unit_from_)) {
graph[f.unit_from_].push_back(edge);
} else {
graph[f.unit_from_] = {edge};
}
std::pair<std::string, double> reversed_edge = {f.unit_from_, 1 / f.ratio_};
if (graph.contains(f.unit_to_)) {
graph[f.unit_to_].push_back(reversed_edge);
} else {
graph[f.unit_to_] = {reversed_edge};
}
}
int N = 0;
std::cin >> N;
for (int i = 0; i < N; ++i) {
std::string from, to;
double quantity;
std::cin >> quantity >> from >> to;
std::set<std::string> visited;
double ans = quantity * coefficient(graph, from, to, visited);
if (ans == 0) {
std::cout << "Either from or to unit is not defined in the rules" << std::endl;
break;
}
std::cout << quantity << " " << from << " is " << ans << " " << to << std::endl;
}
return 0;
}