---
id: 1805
lang: en
translation_of: index.md
source_sha256: 7df1c1a00897d9006fb46f34091369747b85ca9c71d42c0947a55a5d7fb97843
title: "[Codeforces 510D] Fox And Jumping — Solution"
description: "To cover the whole line, the chosen lengths only need to combine into 1; by Bézout's theorem, a DP keeps forming new gcds to find the minimum cost."
tags: ["OI","Math","DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Main Idea

To cover the entire line, we only need these step lengths to be able to combine into a $1$. Then by Bézout's theorem, we have $ax + by = \gcd(a, b)$, so we can use this to do a DP: keep combining into new $\gcd$s to find the minimum cost.

## Code

```cpp
// CF510D.cpp
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 330;

int li[MAX_N], ci[MAX_N], n;
map<int, int> ump;
map<int, int>::iterator it;

int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &li[i]);
    for (int i = 1; i <= n; i++)
        scanf("%d", &ci[i]);
    for (int i = 1; i <= n; i++)
    {
        int tmp = ump[li[i]];
        if (tmp == 0)
            ump[li[i]] = ci[i];
        else
            ump[li[i]] = min(tmp, ci[i]);
        for (it = ump.begin(); it != ump.end(); it++)
        {
            int di = gcd(it->first, li[i]);
            tmp = ump[di];
            if (tmp == 0)
                ump[di] = it->second + ci[i];
            else
                ump[di] = min(tmp, ci[i] + it->second);
        }
    }
    printf("%d", ump[1] ? ump[1] : -1);
    return 0;
}
```
