【Codeforces 290 B】Fox And Jumping

根据裴蜀定理,当且仅当选出来的集合的L[i]的gcd等于1时,才能表示任何数。

考虑普通的dp,dp[i][j]表示前i个数gcd为j的最少花费,j比较大,但状态数不多,拿个map转移就好了。

技巧&套路:

  • 裴蜀定理,gcd为1表示任何数。
  • 当状态数不多的时候,map暴力转移dp。
 1 #include <cstdio>
 2 #include <map>
 3 #include <algorithm>
 4 
 5 const int N = 305;
 6 
 7 int n, l[N], c[N];
 8 std::map<int, int> M;
 9 
10 int gcd(int a, int b) {
11     if (a < b) std::swap(a, b);
12     return (!b)? (a) : (gcd(b, a % b));
13 }
14 
15 int main() {
16     scanf("%d", &n);
17     for (int i = 1; i <= n; ++i) {
18         scanf("%d", &l[i]);
19     }
20     for (int i = 1; i <= n; ++i) {
21         scanf("%d", &c[i]);
22     }
23     for (int i = 1; i <= n; ++i) {
24         for (std::map<int, int>::iterator it = M.begin(); it != M.end(); ++it) {
25             int gc = gcd(it->first, l[i]);
26             if (!M[gc] || M[gc] > it->second + c[i]) {
27                 M[gc] = it->second + c[i];
28             }
29         }
30         if (!M[l[i]] || M[l[i]] > c[i]) {
31             M[l[i]] = c[i];
32         }
33     }
34     if (!M[1]) puts("-1"); else printf("%d\n", M[1]);
35     
36     return 0;
37 }
View Code

猜你喜欢

转载自www.cnblogs.com/Dance-Of-Faith/p/9295876.html