# [NOI2018]屠龙勇士

## [NOI2018]屠龙勇士

$\begin{cases} atk_1*x\equiv a_1(mod\ p_1)\\ atk_2*x\equiv a_2(mod\ p_2)\\ ...\\ atk_n*x\equiv a_n(mod\ p_n) \end{cases}$

emmm,这不难让我们想到$$excrt$$对吧.

$atk_i*(ans+M*x)\equiv a_i(mod\ p_i)$

$atk_i*M*x\equiv a_i-atk_i*ans(mod\ p_i)$

/*
mail: mleautomaton@foxmail.com
author: MLEAutoMaton
This Code is made by MLEAutoMaton
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<iostream>
using namespace std;
#define ll long long
#define REP(a,b,c) for(int a=b;a<=c;a++)
#define re register
#define int ll
#define file(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
inline int gi(){
int f=1,sum=0;char ch=getchar();
while(ch>'9' || ch<'0'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0' && ch<='9'){sum=(sum<<3)+(sum<<1)+ch-'0';ch=getchar();}
return f*sum;
}
const int N=100010;
int multi(int a,int b,int Mod){
int ret=0;
while(b){if(b&1)ret=(ret+a)%Mod;b>>=1;a=(a+a)%Mod;}
return ret;
}
int qpow(int a,int b,int Mod){
int ret=1;
while(b){if(b&1)ret=multi(ret,a,Mod);b>>=1;a=multi(a,a,Mod);}
return ret%Mod;
}
int exgcd(int a,int b,int &x,int &y){
if(!b){x=1;y=0;return a;}
int d=exgcd(b,a%b,y,x);y-=a/b*x;
return d;
}
multiset<int>se;
int c[N],a[N],p[N],n,m,atk[N];
void work(){
for(int i=1;i<=n;i++){
multiset<int>::iterator it=se.upper_bound(a[i]);
if(it!=se.begin())it--;
atk[i]=*it;se.erase(it);se.insert(c[i]);
}
}
int solve(){
ll ans=0,M=1,x,y,d;
for(int i=1;i<=n;i++){
a[i]=(a[i]-multi(atk[i],ans,p[i])+p[i])%p[i];
atk[i]=multi(atk[i],M,p[i]);
d=exgcd(atk[i],p[i],x,y);x=(x%p[i]+p[i])%p[i];
if(a[i]%d)return -1;
ans+=multi(a[i]/d,x,p[i]/d)*M;
M*=p[i]/d;
ans=(ans%M+M)%M;
}
return ans;
}
signed main(){
#ifndef ONLINE_JUDGE
freopen("in.in","r",stdin);
#endif
int T=gi();
while(T--){
n=gi();m=gi();se.clear();
for(int i=1;i<=n;i++)a[i]=gi();
for(int i=1;i<=n;i++)p[i]=gi();
int flag=1;for(int i=1;i<=n;i++)if(a[i]>p[i]){flag=0;break;}
for(int i=1;i<=n;i++)c[i]=gi();
for(int i=1;i<=m;i++)se.insert(gi());
work();
if(!flag){
int ans=0;
for(int i=1;i<=n;i++)
ans=max(ans,(a[i]-1)/atk[i]+1);
printf("%lld\n",ans);
continue;
}
printf("%lld\n",solve());
}
return 0;
}

posted @ 2019-09-17 21:39  QwQGJH  阅读(197)  评论(4编辑  收藏  举报