传送门
题目描述
给定 n n n个数,每个数 a i a_{i} ai都有一个对应的 c o s t i cost_{i} costi,现在你需要从中取若干种数,每种数可以有若干个,将他们相加减可以得到任意一个整数,问你最小的花费是多少
分析
首先我们可以把问题转换成选若干个数凑出一个1,因为凑出来1,就可以凑出来任意个数
根据裴蜀定理我们知道,方程
a
x
+
b
y
=
g
c
d
(
a
,
b
)
ax + by = gcd(a,b)
ax+by=gcd(a,b)存在一组
x
,
y
x,y
x,y使得该等式成立,所以可以得到
g
c
d
(
a
,
b
)
=
=
1
gcd(a,b) == 1
gcd(a,b)==1
所以现在的的问题变成了选若干个数,
g
c
d
gcd
gcd为1的最小花费
说实话我一开始的思路是背包,但是这个
O
(
n
m
)
O(nm)
O(nm)的复杂度明显爆炸了,然后搜了一波题解发现可以用
m
a
p
map
map去优化,有点被秀到了
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod= 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a){char c=getchar();T x=0,f=1;while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
while(isdigit(c)){x=(x<<1)+(x<<3)+c-'0';c=getchar();}a=f*x;}
int gcd(int a,int b){return (b>0)?gcd(b,a%b):a;}
map<int,int> f;
int l[N],c[N];
int n;
int main(){
read(n);
for(int i = 1;i <= n;i++) read(l[i]);
for(int i = 1;i <= n;i++) read(c[i]);
for(int i = 1;i <= n;i++){
f[l[i]] = f[l[i]] ? min(f[l[i]],c[i]) : c[i];
for(auto t:f){
int p = __gcd(t.fi,l[i]);
f[p] = f[p] ? min(t.se + c[i],f[p]) : t.se + c[i];
}
}
if(!f[1]) f[1] = -1;
di(f[1]);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/