Description
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length l i and cost c i. If she pays c i dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length l i l_i li, i. e. from cell x to cell ( x − l i ) (x - l_i) (x − li) or cell ( x + l i ) (x + l_i) (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer
n
(
1
≤
n
≤
300
)
n (1 ≤ n ≤ 300)
n(1 ≤ n ≤ 300), number of cards.
The second line contains n numbers l i ( 1 ≤ l i ≤ 1 e 9 ) l_i (1 ≤ l_i ≤ 1e9) li(1 ≤ li ≤ 1e9), the jump lengths of cards.
The third line contains n numbers c i ( 1 ≤ c i ≤ 1 e 5 ) c_i (1 ≤ c_i ≤ 1e5) ci(1 ≤ ci ≤ 1e5), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Solution
显然需要凑出1来才可以到达数轴上所有的点
又根据裴蜀定理,只有选出的数的
g
c
d
=
=
1
gcd == 1
gcd==1 才能满足条件
设
d
p
[
i
]
dp[i]
dp[i] :凑出
g
c
d
=
=
i
gcd == i
gcd==i 所需要的最少花费, 再利用map来离散化
g
c
d
gcd
gcd
Code
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
using namespace std;
const int MX = 300 + 7;
ll gcd(ll a,ll b){return b ? gcd(b,a%b):a;}
int l[MX],c[MX];
map<int,int>dp;
int main(){
int n;scanf("%d",&n);
for(int i = 1;i <= n;++i) scanf("%d",&l[i]);
for(int i = 1;i <= n;++i) scanf("%d",&c[i]);
map<int,int>::iterator it;
dp[0] = 0;
for(int i = 1;i <= n;++i){
for(it = dp.begin();it != dp.end();++it){
int cost = c[i] + it->second;
int g = gcd(l[i],it->first);
if(dp[g] && cost >= dp[g]) continue;
dp[g] = cost;
}
}
int res = dp[1];
if(!res) printf("-1\n");
else printf("%d\n", res);
return 0;
}