#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 42, logn = 23;
int c[maxn], v[maxn], dp[maxn];
int last_v[logn];
vector<int> last_c[maxn];
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> c[i];
for(int i = 0; i < n; i++)
cin >> v[i];
int st = 0;
for(int i = 0; i < n; i++)
{
last_c[c[i]].push_back(i + 1);
if(last_c[c[i]].size() >= 2)
st = max(st, last_c[c[i]][last_c[c[i]].size() - 2]);
dp[i + 1] = dp[i] + v[i];
pair<int, int> tv[logn];
for(int j = 0; j < logn; j++)
tv[j] = {last_v[j], j};
sort(tv, tv + logn, greater<pair<int, int>>());
int cur = v[i];
for(int j = 0; tv[j].first; j++)
{
cur |= 1 << tv[j].second;
if(tv[j].first == tv[j + 1].first)
continue;
dp[i + 1] = min(dp[i + 1], dp[max(st, tv[j + 1].first)] + cur);
}
for(int z = 0; z < logn; z++)
if((v[i] >> z) & 1)
last_v[z] = i + 1;
}
cout << dp[n] << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+Cgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IG1heG4gPSAxZTYgKyA0MiwgbG9nbiA9IDIzOwppbnQgY1ttYXhuXSwgdlttYXhuXSwgZHBbbWF4bl07CmludCBsYXN0X3ZbbG9nbl07CnZlY3RvcjxpbnQ+IGxhc3RfY1ttYXhuXTsKCnNpZ25lZCBtYWluKCkKewogICAgaW9zOjpzeW5jX3dpdGhfc3RkaW8oMCk7CiAgICBjaW4udGllKDApOwogICAgaW50IG47CiAgICBjaW4gPj4gbjsKICAgIGZvcihpbnQgaSA9IDA7IGkgPCBuOyBpKyspCiAgICAgICAgY2luID4+IGNbaV07CiAgICBmb3IoaW50IGkgPSAwOyBpIDwgbjsgaSsrKQogICAgICAgIGNpbiA+PiB2W2ldOwogICAgaW50IHN0ID0gMDsKICAgIGZvcihpbnQgaSA9IDA7IGkgPCBuOyBpKyspCiAgICB7CiAgICAgICAgbGFzdF9jW2NbaV1dLnB1c2hfYmFjayhpICsgMSk7CiAgICAgICAgaWYobGFzdF9jW2NbaV1dLnNpemUoKSA+PSAyKQogICAgICAgICAgICBzdCA9IG1heChzdCwgbGFzdF9jW2NbaV1dW2xhc3RfY1tjW2ldXS5zaXplKCkgLSAyXSk7CiAgICAgICAgZHBbaSArIDFdID0gZHBbaV0gKyB2W2ldOwogICAgICAgIHBhaXI8aW50LCBpbnQ+IHR2W2xvZ25dOwogICAgICAgIGZvcihpbnQgaiA9IDA7IGogPCBsb2duOyBqKyspCiAgICAgICAgICAgIHR2W2pdID0ge2xhc3RfdltqXSwgan07CiAgICAgICAgc29ydCh0diwgdHYgKyBsb2duLCBncmVhdGVyPHBhaXI8aW50LCBpbnQ+PigpKTsKICAgICAgICBpbnQgY3VyID0gdltpXTsKICAgICAgICBmb3IoaW50IGogPSAwOyB0dltqXS5maXJzdDsgaisrKQogICAgICAgIHsKICAgICAgICAgICAgY3VyIHw9IDEgPDwgdHZbal0uc2Vjb25kOwogICAgICAgICAgICBpZih0dltqXS5maXJzdCA9PSB0dltqICsgMV0uZmlyc3QpCiAgICAgICAgICAgICAgICBjb250aW51ZTsKICAgICAgICAgICAgZHBbaSArIDFdID0gbWluKGRwW2kgKyAxXSwgZHBbbWF4KHN0LCB0dltqICsgMV0uZmlyc3QpXSArIGN1cik7CiAgICAgICAgfQogICAgICAgIGZvcihpbnQgeiA9IDA7IHogPCBsb2duOyB6KyspCiAgICAgICAgICAgIGlmKCh2W2ldID4+IHopICYgMSkKICAgICAgICAgICAgICAgIGxhc3Rfdlt6XSA9IGkgKyAxOwogICAgfQogICAgY291dCA8PCBkcFtuXSA8PCBlbmRsOwoJcmV0dXJuIDA7Cn0=