fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. ll n,a[509],c[509];
  5. ll calc(ll a,ll b)
  6. {
  7. if(b>a)return calc(b,a);
  8. ll t;
  9. while(b)
  10. {
  11. t=a%b;
  12. a=b;
  13. b=t;
  14. }
  15. return a;
  16. }
  17. map<ll,ll> m,b;//gcd,sum of c
  18. int main()
  19. {
  20. #define int long long
  21. cin>>n;
  22. for(int i=1;i<=n;i++)cin>>a[i];
  23. for(int i=1;i<=n;i++)cin>>c[i];
  24. int ans=INT_MAX;
  25. for(int i=1;i<=n;i++)
  26. {
  27. m.clear();
  28. if(a[i]==1)ans=min(ans,c[i]);
  29. //else m[a[i]]=c[i];
  30. for(map<int,int>::iterator it=b.begin();it!=b.end();it++)
  31. {
  32. int val=calc(it->first,a[i]);
  33. if(val==1)
  34. ans=min(ans,it->second+c[i]);
  35. if(b.find(val)==b.end())
  36. if(m.find(val)==m.end())
  37. m[val]=it->second+c[i];
  38. else
  39. m[val]=min(m[val],it->second+c[i]);
  40. else
  41. b[val]=min(b[val],it->second+c[i]);
  42. }
  43. if(b.find(a[i])==b.end())
  44. b[a[i]]=c[i];
  45. else b[a[i]]=min(b[a[i]],c[i]);
  46. for(map<int,int>::iterator it=m.begin();it!=m.end();it++)
  47. b[it->first]=it->second;
  48. }
  49. if(ans==INT_MAX)cout<<-1<<endl;
  50. else cout<<ans<<endl;
  51. return 0;
  52. }
Success #stdin #stdout 0s 3472KB
stdin
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
stdout
7237