//xhz.cpp
#include<bits/stdc++.h>
using namespace std;
int n,m,c,a[1000003],b[1000003];
void solve(){
cin>>n>>m>>c;
for(int i=0;i<n;i++)cin>>a[i];
for(int i=0;i<n;i++)cin>>b[i];
map<int,long long>mp;
mp[0]=m;
long long ans=0;
for(int i=0;i<n;i++){
int tmp=b[i];
while(mp.size()){
auto it=mp.begin();
if((it->first+1)*(it->second)<=b[i]){
ans+=it->first*it->second;
b[i]-=(it->first+1)*(it->second);
mp.erase(it);
}else{
int t=it->first;
it->second-=b[i]/(t+1)+1;
ans+=b[i]/(t+1)*t;
b[i]%=(t+1);
int f=c-(a[i]-tmp+b[i])%c;
if(c-f-b[i]<=0){
ans+=c-f;
b[i]-=c-f;
mp[t+f-c]++;
}else if(t-b[i]<=f||b[i]+f>tmp){
ans+=b[i];
mp[t-b[i]]++;b[i]=0;
}else mp[t]++;
if(!it->second)mp.erase(t);
break;
}
}tmp-=b[i];
tmp=a[i]-tmp;
ans+=tmp;
mp[0]+=tmp/c;
if(tmp%c!=0&&(tmp/c+1)*c<=a[i]){
mp[(tmp/c+1)*c-tmp]++;
tmp=(tmp/c+1)*c;
}mp[c]+=(a[i]-tmp)/c;
}
cout<<ans<<'\n';
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;cin>>T;
while(T--)solve();
}