传送:点击打开链接
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.
题意:
在一个无限长的线段上,每个格子用一个整数标号。初始在0点。给出n个卡片。有属性l[i]和它们的花费c[i]。花费c[i]的钱可以买到可以左右移动l[i]的卡片。问最少需要多少钱,能访问到所有的点。
思路:能访问到所有的点,意思就是选出的l[i]的gcd为1。目的就转化为选一些数,使它们的gcd=1,并且花费最小。用dp[i]来表示构成数i所需要的最小花费。由于i很大,但是各个数之间的密度并不大,可以用map来存。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
int gcd(int a,int b)
{
if(b==0) return a;
else return gcd(b,a%b);
}
int l[305],c[305];
int main()
{
int n;
scanf("%d",&n);
int tmp=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&l[i]);
tmp=gcd(tmp,l[i]);
}
if(tmp!=1)
{
printf("-1\n");
return 0;
}
for(int i=1;i<=n;i++)
{
scanf("%d",&c[i]);
}
map<int,int>mm;
for(int i=1;i<=n;i++)
{
auto it=mm.find(l[i]);
if(it!=mm.end())
{
if(c[i]<it->second) it->second=c[i];
}
else
mm.insert(make_pair(l[i],c[i]));
}
int ans=0x7FFFFFFF;
if(mm.find(1)!=mm.end()) ans=mm[1];
for(int i=1;i<=n;i++)
{
for(auto it=mm.begin();it!=mm.end();it++)
{
int L=gcd(it->first,l[i]);
int C=it->second+c[i];
auto is=mm.find(L);
if(is==mm.end())
{
mm[L]=C;
}
else
{
if(C<is->second) is->second=C;
}
if(L==1&&C<ans) ans=C;
}
}
printf("%d\n",ans);
return 0;
}