// ~~ icebear ~~
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef pair<ii, int> iii;
#define FOR(i,a,b) for(int i=(a); i<=(b); ++i)
#define FORR(i,a,b) for(int i=(a); i>=(b); --i)
#define rep(i, n) for(int i=0; i<(n); ++i)
#define red(i, n) for(int i=(n)-1; i>=0; --i)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define task "icebearat"
const int MOD = 1e9 + 7;
const int inf = 1e9 + 27092008;
const ll LLinf = 1e18 + 27092008;
const int N = 1e6 + 5;
const int LG = 27;
int n, k;
int a[N], c[N];
int rmq[N][LG];
deque<int> dq;
ll dp[N];
void push(int id) {
while(!dq.empty() && dp[dq.back()] >= dp[id]) dq.pop_back();
dq.pb(id);
}
int get(int l, int r) {
int k = __lg(r - l + 1);
return (rmq[l][k] & rmq[r - (1 << k) + 1][k]);
}
void solve() {
cin >> n >> k;
FOR(i,1,n) cin >> a[i];
FOR(i,1,n) cin >> c[i];
FOR(i,1,n) {
dp[i] = LLinf;
rmq[i][0] = a[i];
}
dq.clear();
FOR(j,1,__lg(n))
FOR(i,1,n - (1<<j) + 1)
rmq[i][j] = (rmq[i][j-1] & rmq[i + (1 << (j-1))][j-1]);
dq.pb(0);
FOR(i,1,n) {
if (get(i, min(i+k-1, n)) == 0) dp[i] = dp[i-1];
if (!dq.empty() && dq.front() < i - k) dq.pop_front();
if (!dq.empty()) dp[i] = min(dp[i], c[i] + dp[dq.front()]);
push(i);
}
cout << *min_element(dp + n - k + 1, dp + n + 1) << '\n';
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
if (fopen(task".inp", "r")){
freopen(task".inp", "r", stdin);
freopen(task".out", "w", stdout);
}
int tc = 1;
cin >> tc;
while(tc--) solve();
return 0;
}
Ly8gfn4gaWNlYmVhciB+fgojaW5jbHVkZSA8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZD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pIHsKICAgIGNpbiA+PiBuID4+IGs7CiAgICBGT1IoaSwxLG4pIGNpbiA+PiBhW2ldOwogICAgRk9SKGksMSxuKSBjaW4gPj4gY1tpXTsKICAgIEZPUihpLDEsbikgewogICAgICAgIGRwW2ldID0gTExpbmY7CiAgICAgICAgcm1xW2ldWzBdID0gYVtpXTsKICAgIH0KICAgIGRxLmNsZWFyKCk7CgogICAgRk9SKGosMSxfX2xnKG4pKQogICAgICAgIEZPUihpLDEsbiAtICgxPDxqKSArIDEpICAKICAgICAgICAgICAgcm1xW2ldW2pdID0gKHJtcVtpXVtqLTFdICYgcm1xW2kgKyAoMSA8PCAoai0xKSldW2otMV0pOwoKICAgIGRxLnBiKDApOwogICAgRk9SKGksMSxuKSB7CiAgICAgICAgaWYgKGdldChpLCBtaW4oaStrLTEsIG4pKSA9PSAwKSBkcFtpXSA9IGRwW2ktMV07CiAgICAgICAgaWYgKCFkcS5lbXB0eSgpICYmIGRxLmZyb250KCkgPCBpIC0gaykgZHEucG9wX2Zyb250KCk7CiAgICAgICAgaWYgKCFkcS5lbXB0eSgpKSBkcFtpXSA9IG1pbihkcFtpXSwgY1tpXSArIGRwW2RxLmZyb250KCldKTsKICAgICAgICBwdXNoKGkpOwogICAgfSAKCiAgICBjb3V0IDw8ICptaW5fZWxlbWVudChkcCArIG4gLSBrICsgMSwgZHAgKyBuICsgMSkgPDwgJ1xuJzsKfQoKaW50IG1haW4oKSB7CiAgICBpb3NfYmFzZTo6c3luY193aXRoX3N0ZGlvKDApOwogICAgY2luLnRpZSgwKTsgY291dC50aWUoMCk7CiAgICBpZiAoZm9wZW4odGFzayIuaW5wIiwgInIiKSl7CiAgICAgICAgZnJlb3Blbih0YXNrIi5pbnAiLCAiciIsIHN0ZGluKTsKICAgICAgICBmcmVvcGVuKHRhc2siLm91dCIsICJ3Iiwgc3Rkb3V0KTsKICAgIH0KICAgIGludCB0YyA9IDE7CiAgICBjaW4gPj4gdGM7CiAgICB3aGlsZSh0Yy0tKSB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