#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;
}