每种操作的权值是2k2k,这个很有意思,说明如果我存在一种方案,使得用k以下的能完成任务,那我一定不会用k,因为∑k−1i=02i<2k∑i=0k−12i<2k
于是我们考虑枚举答案,从大向小枚举,假设当前枚举到k,我们判断如果不用k行不行,就把大于k的已经被选中的方案和1~k-1的所有方案都作为备选方案,做一遍dp
dp[i][j][k]表示对于第i个数,已经考虑过前k种备选方案(方案从大到小排序)后,能不能使得余数为k,那么dp[i][j][k]−>dp[i][j+1][k]dp[i][j][k]−>dp[i][j+1][k]和dp[i]]j][k]−>dp[i][j+1][kdp[i]]j][k]−>dp[i][j+1][k的转移是明显的
如果对于每个数都有dp[tot][a[i]][b[i]]=true,那么说明存在方案不选k,那我们就一定不选k,否则就不得不选k
这样就做完了,要记得判断-1的情况:b[i]*2+1>a[i] && b[i]!=a[i]
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <utility>
#include <cctype>
#include <algorithm>
#include <bitset>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <cmath>
#define LL long long
#define LB long double
#define x first
#define y second
#define Pair pair<int,int>
#define pb push_back
#define pf push_front
#define mp make_pair
#define LOWBIT(x) x & (-x)
using namespace std;
const int MOD=1e9+7;
const LL LINF=2e16;
const int INF=2e9;
const int magic=348;
const double eps=1e-10;
const double pi=3.14159265;
inline int getint()
{
char ch;int res;bool f;
while (!isdigit(ch=getchar()) && ch!='-') {}
if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
while (isdigit(ch=getchar())) res=res*10+ch-'0';
return f?res:-res;
}
int n;
int a[58],b[58];
bool Dp[58][58];
int valid[58],vtot;
int anslist[58],tot;
inline bool judge()
{
int res=-1;
int i,j,k,cc;
for (i=1;i<=n;i++)
{
memset(Dp,false,sizeof(Dp));
Dp[0][a[i]]=true;
for (j=0;j<=vtot-1;j++)
for (k=0;k<=50;k++)
if (Dp[j][k])
{
Dp[j+1][k]=true;
Dp[j+1][k%valid[j+1]]=true;
}
if (!Dp[vtot][b[i]]) return false;
}
return true;
}
int main ()
{
n=getint();int i,calc;
for (i=1;i<=n;i++) a[i]=getint();
for (i=1;i<=n;i++) b[i]=getint();
for (i=1;i<=n;i++) if (b[i]*2+1>a[i] && b[i]!=a[i]) {printf("-1\n");return 0;}
tot=0;
for (calc=50;calc>0;calc--)
{
vtot=0;for (i=1;i<=tot;i++) valid[++vtot]=anslist[i];
for (i=calc-1;i;i--) valid[++vtot]=i;
if (judge()) continue;
anslist[++tot]=calc;
}
LL ans=0;for (i=1;i<=tot;i++) ans+=(1ll<<anslist[i]);
printf("%lld\n",ans);
return 0;
}