Codeforces 512B Fox And Jumping dp + gcd, codeforces512b
Question link: Click the open link
Question:
Given n count
The following two rows represent n numbers and the cost of purchasing these numbers.
This allows you to obtain any positive integer by adding or subtracting numbers. Ask the minimum cost. (The purchased number can be used multiple times)
Ideas:
First, we need to obtain any positive integer. In fact, we can get 1.
To get 1, we only need to select the number of gcd = 1.
Given integers x and y, to make x y construct any integer, the required condition is gcd (x, y) = 1.
Inference:
Set int G = gcd (x, y );
Then ax + by = G (ax/G + by/G)
Any integer in parentheses. When G = 1, the ax + by can constitute 1.
Then, the minimum cost for each gcd in the dynamic maintenance set.
#include <cstdio>#include <cstring>#include <string.h>#include <iostream>#include <algorithm>#include <queue>#include <vector>#include <cmath>#include <set>#include <map>using namespace std;int l[306];int c[306];int gcd(int a,int b){ return b==0?a:gcd(b,a%b);}map<int,int>mp[2];map<int,int>::iterator it;int pre,cur;int hehe; int papa;void setMin(int x,int y){ if(mp[cur].count(x)) { if(y<mp[cur][x]) mp[cur][x]=y; } else mp[cur][x]=y;}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]); pre=0;cur=1; mp[0][l[1]]=c[1]; for(int i=2;i<=n;i++) { mp[cur].clear(); mp[cur][l[i]]=c[i]; for(it=mp[pre].begin();it!=mp[pre].end();it++) { int x=it->first; int y=it->second; setMin(x,y); setMin(gcd(x,l[i]),y+c[i]); } swap(pre,cur); } if(!mp[pre].count(1)) puts("-1"); else printf("%d\n",mp[pre][1]);}