Codeforces_512_B
http://codeforces.com/problemset/problem/512/B
dp题,因为状态很多,所以用map保存,注意代码中的那个二层循环不能内外换,因为map会自动排序。
#include<iostream> #include<cstdio> #include<map> using namespace std; int gcd(int a,int b) { return b?gcd(b,a%b):a; } int l[305],c[305]; int main() { int n; cin >> n; for(int i = 1;i <= n;i++) cin >> l[i]; for(int i = 1;i <= n;i++) cin >> c[i]; map<int,int> mp; mp.clear(); map<int,int>::iterator it; mp[0] = 0; for(int i = 1;i <= n;i++) { for(it = mp.begin();it != mp.end();it++) { int temp = gcd(l[i],it->first); if(mp.count(temp)) mp[temp] = min(mp[temp],it->second+c[i]); else mp[temp] = it->second+c[i]; } } if(mp.count(1)) printf("%d\n",mp[1]); else printf("-1\n"); return 0; }