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.
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.
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.
3 100 99 9900 1 1 1
2
5 10 20 30 40 50 1 1 1 1 1
-1
7 15015 10010 6006 4290 2730 2310 1 1 1 1 1 1 1 10
6
8 4264 4921 6321 6984 2316 8432 6120 1026 4264 4921 6321 6984 2316 8432 6120 1026
7237
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
题目大意:
给你N个数,每个数用的话需要花费ci,如果他站在x位子,选取了ai,那么他可以选择走到(x+ai)或者是(x-ai),走的次数不限。
问一开始他站在原点,能否通过选取一些数字使得他能够走到任意位子。
思路:
1、稍微有点数论基础的同学一定知道,如果一些数字的gcd==1,就可以达到目标,使得主人公可以走到任意位置。
那么问题就转化变成:用最小的花费找一些数,使得他们的gcd==1.
2、那么接下来考虑dp,设定dp【i】【j】表示选到第i个数字的时候,gcd值为j的最小花费。
显然直接设定是要爆内存的,那么再考虑一点,j这个值一定是ai的因子数。
我们又知道,一个数字的因子数个数不超过log2n个,n最大为300.那么最多可能gcd出来的值也并不多。
所以我们预处理出所有数字的因子数,放到一个数组中并且用map映射位子即可。
那么有(s[gcd(num【j】,a【i+1】)]表示的是gcd两个数的值所在num【】数组中的位子):
dp【i+1】【s[gcd(num【j】,a【i+1】)]】=min(dp【i+1】【s[gcd(num【j】,a【i+1】)]】,dp【i】【j】+val【i+1】);
3、注意数据的初始化,以及细节的处理就没别的可说的了。
Ac代码:
#include
#include
#include