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 li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (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), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), 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
题意:在一条无限长的线上,给你一些牌,牌的作用是花费一定钱买,使用时可以向左或者向右走一定值。问你在给定的这些牌中怎么选择可以使花费最小且可以到任意一点。
思路:
意图很明显,想到达任何一点,就需要卡片的组合可以使移动距离为1,变成了GCD(X1,X2,…Xn)==1的问题,那么这里用的暴力实现的,用到map的迭代器。因为卡牌的步数限定在1e9的范围内,这里每次更新已经可以到达的加上当前卡片可以到最小值花费,通过map的离散化扫描加上不断更细实现任意Xi求GCD的情况,最后观察dp[1]的情况即可。
还是暴力大法好,据说这题应该是数论+状压dp,准备学习一发
#include<bits/stdc++.h>
#define input freopen("input.txt","r",stdin)
using namespace std;
int value[330][2],n;
map<int,int>dp;
int gcd(int a,int b){
if(b==0) return a; //这样每次求GCD(A,0)的情况直接返回A,相当于只选择一种牌
return a%b==0?b:gcd(b,a%b);
}
int main(){
input;
int i,j;
while(scanf("%d",&n)!=EOF){
for(i=1;i<=n;i++){
scanf("%d",&value[i][0]);
}
for(i=1;i<=n;i++){
scanf("%d",&value[i][1]);
}
dp.clear();
map<int,int> ::iterator it;
dp[0]=0; //初始化 ,让迭代器中有数值
for(i=1;i<=n;i++){
int x=value[i][0];
for(it=dp.begin();it!=dp.end();it++){
int y=it->first;
int m=gcd(x,y);
if(dp[m]!=0&&dp[it->first]+value[i][1]>dp[m]) continue; //当选择后情况不是最优解跳过
dp[m]=dp[it->first]+value[i][1];
}
}
if(dp[1]==0) cout<<-1<<endl;
else cout<<dp[1]<<endl;
}
return 0;
}