#include <bits/stdc++.h>
#define ll long long
#define pll pair<ll,ll>
#define f first
#define s second
using namespace std;
const ll N=1e6+10;
ll t,n,a[N],b[N],l,r,mid,ans;
deque<ll> q;
bool check(ll mid){
q.clear();
ll k=1,coin=0,bef=b[1];//coin是剩余,lef是当前位置的天数
for(ll i=1;i<=n;i++){
while(!q.empty()&&a[q.back()]<a[i]){
q.pop_back();
}
q.push_back(i);
ll need=mid;//需要花的钱数
if(need<=coin){
coin-=need;
need=0;
}else{
need-=coin;
coin=0;
}
while(need){
if(bef*a[q.front()]>=need){
ll cost=ceil(need*1.0/a[q.front()]);//数学公式
bef-=cost;
coin+=cost*a[q.front()]-need;
need=0;
}else{
need-=bef*a[q.front()];
k++;
bef=b[k];
if(q.front()<k){
q.pop_front();
}
if(k>i){
return 0;
}
}
}
}
return 1;
}
signed main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--){
cin>>n;
for(ll i=1;i<=n;i++){
cin>>a[i];
}
for(ll i=1;i<=n;i++){
cin>>b[i];
}
l=0,r=1e15;
while(l<=r){
mid=l+r>>1;
if(check(mid)){
l=mid+1;
ans=mid;
}else{
r=mid-1;
}
}
cout<<ans<<'\n';
}
return 0;
}
麻烦大佬们优化一下!