Codeforces 510D. Fox And Jumping (DP + 裴蜀定理 + 离散化)

23 篇文章 0 订阅

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) (xli) 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(1n300), number of cards.

The second line contains n numbers l i ( 1   ≤   l i   ≤   1 e 9 ) l_i (1 ≤ l_i ≤ 1e9) li(1li1e9), 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(1ci1e5), 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值