-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfox_and_jumping.cpp
More file actions
96 lines (86 loc) · 2.27 KB
/
Copy pathfox_and_jumping.cpp
File metadata and controls
96 lines (86 loc) · 2.27 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//============================================================================
// Name : test.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <set>
#include <tuple>
#include <queue>
#include <map>
int gcd(int a, int b)
{
while (b != 0)
{
auto tmp = b;
b = a % b;
a = tmp;
}
return a;
}
int set_gcd(std::set<int> const & s)
{
auto ret = 0;
for(auto number : s)
ret = gcd (ret, number);
return ret;
}
typedef std::tuple<int, int, std::set<int>> solution;
typedef std::priority_queue<solution, std::vector<solution>, std::greater<solution>> min_heap;
int solve(std::map<int, int> const & cards_costs)
{
min_heap heap;
std::set<int> card_set;
int cost, gcd;
heap.push(solution());
std::map<int, int> memo;
while(!heap.empty())
{
std::tie(cost, gcd, card_set) = heap.top(); heap.pop();
// base case
if (gcd == 1) return cost;
// look for the result
for (auto card_cost : cards_costs)
{
if (!card_set.count(card_cost.first))
{
auto s = card_set;
s.insert(card_cost.first);
auto c = cost + card_cost.second;
gcd = set_gcd(s);
if (memo.find(gcd) == memo.end() || memo[gcd] > c)
{
memo[gcd] = c;
heap.push(solution(c, gcd, s));
}
}
}
}
return -1;
}
int main(int argc, char* argv[])
{
std::map<int, int> cards_costs;
std::vector<int> cards, costs;
auto size = 0;
std::cin >> size;
for (int i = 0; i < size; ++i)
{
int tmp;
std::cin >> tmp;
cards.push_back(tmp);
}
for (int i = 0; i < size; ++i)
{
int tmp;
std::cin >> tmp;
costs.push_back(tmp);
}
for (size_t i = 0; i < cards.size(); ++i)
if (cards_costs.find(cards[i]) == cards_costs.end() || cards_costs[cards[i]] > costs[i])
cards_costs[cards[i]] = costs[i];
std::cout << solve(cards_costs) << std::endl;
return 0;
}