Codeforces 510D map进行DP

传送:点击打开链接

D. Fox And Jumping
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

题意:

在一个无限长的线段上,每个格子用一个整数标号。初始在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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值