#include <iostream>
#include <vector>

const int MAX_N = 100000;

std::vector<int> G[1 + MAX_N];
long long val[1 + MAX_N];
int in[1 + MAX_N];
int out[1 + MAX_N];
long long ans;

int main() {

  int n, m;
  std::cin >> n >> m;
  for (int i = 1; i <= m; i++) {
    int u, v;
    std::cin >> u >> v;
    G[std::min(u, v)].push_back(std::max(u, v));
    out[std::min(u, v)]++;
    in[std::max(u, v)]++;
  }
  for (int i = 1; i <= n; i++) {
    ans += 1LL * in[i] * out[i];
    val[i] = i;
  }
  std::cout << ans << '\n';
  int Q;
  std::cin >> Q;
  for (int q = 1; q <= Q; q++) {
    int u;
    std::cin >> u;
    ans -= 1LL * in[u] * out[u];
    for (int v : G[u])
      if (val[v] > val[u]) {
        ans -= 1LL * in[v] * out[v];
        in[v]--;
        out[v]++;
        ans += 1LL * in[v] * out[v];
        G[v].push_back(u);
      }
    in[u] += out[u];
    out[u] = 0;
    val[u] = n + q;
    G[u].clear();
    std::cout << ans << '\n';
  }

  return 0;
}


//Link : https://codeforces.com/contest/1253

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100005
/*
#include <limits.h>
INT_MAX
LLONG_MAX
*/
set<int> s[N];
int deg[N];

void solve() {
  int n,m;
  scanf("%d %d ", &n,&m);
  for(int i=0;i<m;++i) {
    int a,b;
    scanf("%d %d ", &a,&b);
    ++deg[a];
    ++deg[b];
    if(a>b) {
      swap(a,b);
    }
    assert(a<b);
    s[a].insert(b);
  }
  ll ret = 0;
  for(int i=1;i<=n;++i) {
    ret += (ll)(deg[i]-s[i].size())*s[i].size();
  }
  int q;
  scanf("%d ", &q);
  printf("%lld\n",ret);
  for(int i=n+1;i<=n+q;++i) {
    int v;scanf("%d ", &v);
    ret -= (ll)(deg[v]-s[v].size())*s[v].size();
    int g = deg[v] - s[v].size();
    for(int ch : s[v]) {
      ret -= s[ch].size();
      s[ch].insert(v);
      ret += (deg[ch] - s[ch].size());
    }
    s[v].clear();
    printf("%lld\n", ret);
  }
}

int main() {
    //freopen("input.txt","r",stdin);
    solve();
    return 0;
}


//Link : https://codeforces.com/contest/1253

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100005
/*
#include <limits.h>
INT_MAX
LLONG_MAX
*/
set<int> s[N];
int deg[N];

void solve() {
  int n,m;
  scanf("%d %d ", &n,&m);
  for(int i=n;i;--i) {
    cur[i] = i;
  }
  for(int i=0;i<m;++i) {
    int a,b;
    scanf("%d %d ", &a,&b);
    ++deg[a];
    ++deg[b];
    if(a>b) {
      swap(a,b);
    }
    assert(a<b);
    s[a].insert(b);
  }
  ll ret = 0;
  for(int i=1;i<=n;++i) {
    ret += (ll)(deg[i]-s[i].size())*s[i].size();
  }
  int q;
  scanf("%d ", &q);
  printf("%lld\n",ret);
  for(int i=n+1;i<=n+q;++i) {
    int v;scanf("%d ", &v);
    ret -= (ll)(deg[v]-s[v].size())*s[v].size();
    int g = deg[v] - s[v].size();
    for(int ch : s[v]) {
      ret -= s[ch].size();
      s[ch].insert(v);
      ret += (deg[ch] - s[ch].size());
    }
    s[v].clear();
    printf("%lld\n", ret);
  }
}

int main() {
    //freopen("input.txt","r",stdin);
    solve();
    return 0;
}


//Link : https://codeforces.com/contest/1253

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100005
/*
#include <limits.h>
INT_MAX
LLONG_MAX
*/
set<int> s[N];
int cur[N],deg[N];
ll ad[N];

void solve() {
  int n,m;
  scanf("%d %d ", &n,&m);
  for(int i=n;i;--i) {
    cur[i] = i;
  }
  for(int i=0;i<m;++i) {
    int a,b;
    scanf("%d %d ", &a,&b);
    ++deg[a];
    ++deg[b];
    if(a>b) {
      swap(a,b);
    }
    assert(a<b);
    s[a].insert(b);
  }
  for(int i=n;i;--i) {
    for(int p : s[i]) {
      ad[p] += (deg[i]-s[i].size());
    }
  }
  ll ret = 0;
  for(int i=1;i<=n;++i) {
    ret += (ll)(deg[i]-s[i].size())*s[i].size();
  }
  int q;
  scanf("%d ", &q);
  printf("%lld\n",ret);
  for(int i=n+1;i<=n+q;++i) {
    int v;scanf("%d ", &v);
    ret -= (ll)(deg[v]-s[v].size())*s[v].size();
    int g = deg[v] - s[v].size();
    for(int ch : s[v]) {
      ret -= s[ch].size();
      ad[ch] -= g;
      s[ch].insert(v);
      ad[v] += (deg[ch] - s[ch].size());
      ret += (deg[ch] - s[ch].size());
    }
    cur[v] = i;
    s[v].clear();
    printf("%lld\n", ret);
  }
}

int main() {
    //freopen("input.txt","r",stdin);
    solve();
    return 0;
}


//Link : https://codeforces.com/contest/1253

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 100005
/*
#include <limits.h>
INT_MAX
LLONG_MAX
*/
set<int> s[N];
int deg[N],cur[N],indeg[N];
int a[N],b[N];
bool vis[N],ch[N];
const int SQ = 400;
vector<int> tdj[N];

vector<int> adj[N];

ll clear(int n,int m) {
  for(int i=n;i;--i) {
    vis[i] = false;
    ch[i] = false;
    indeg[i] = 0;
    adj[i].clear();
  }
  for(int i=0;i<m;++i) {
    if(cur[a[i]]<cur[b[i]]) {
      ++indeg[a[i]];
    } else {
      ++indeg[b[i]];
    }
  }
  ll ret = 0;
  for(int i=n;i;--i) {
    ret += (ll)(deg[i]-indeg[i])*indeg[i];
  }
  return ret;
}

int v[N];
void solve() {
  int n,m;
  scanf("%d %d ", &n,&m);
  for(int i=n;i;--i) {
    cur[i] = i;
  }
  for(int i=0;i<m;++i) {
    scanf("%d %d ", &a[i],&b[i]);
    ++deg[a[i]];
    ++deg[b[i]];
    tdj[a[i]].push_back(b[i]);
    tdj[b[i]].push_back(a[i]);
  }
  int q;
  scanf("%d ", &q);
  ll ret = clear(n,m);
  printf("%lld\n",ret);
  for(int i=1;i<=q;++i) {
    scanf("%d ", &v[i]);
  }
  for(int i=1;i<=q;) {
    int ed = min(i + SQ-1,q);
    if(i!=1)
      ret = clear(n,m);
    int pos = 0;
    for(int j=i;j<=ed;++j) {
      ch[v[j]] = true;
    }
    for(int j=1;j<=n;++j) {
      if(ch[j]) {
        for(int node : tdj[j]) {
          if(ch[node]) {
            adj[j].push_back(node);
          }
        }
      }
    }
    for(int j=i;j<=ed;++j) {
      int node = v[j];
      ret -= (ll)(deg[node]-indeg[node])*indeg[node];
      if(!vis[node]) {
        vis[node] = true;
        for(int anode : tdj[node]) {
          if(ch[anode] || cur[node]>cur[anode]) {
            continue;
          }
          ret -= indeg[anode];
          ++indeg[anode];
          ret += (deg[anode] - indeg[anode]);
        }
      }
      for(int anode : adj[node]) {
        if(cur[node]<cur[anode]) {
          ret -= indeg[anode];
          ++indeg[anode];
          ret += (deg[anode] - indeg[anode]);
        }
      }
      indeg[node] = 0;
      cur[node] = n + j;
      printf("%lld\n", ret);
    }
    i = ed + 1;
  }
}

int main() {
    //freopen("input.txt","r",stdin);
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int M=200005;
int n,m,in[M],out[M]; ll ans;
vector<int> v[M];
int main()
{
    scanf("%d%d",&n,&m);
    while(m--)
    {
        int a,b; scanf("%d%d",&a,&b);
        if(a>b) swap(a,b);
        v[a].push_back(b);
        out[a]++,in[b]++;
        ans+=in[a]+out[b];
    }
    printf("%lld\n",ans);
    int q; scanf("%d",&q);
    while(q--)
    {
        int x; scanf("%d",&x);
        for(int i=0;i<v[x].size();i++)
        {
            int y=v[x][i];
            if(!y) continue;
            v[x][i]=0;
            ans-=in[x]+out[y];
            out[x]--,in[y]--;
            v[y].push_back(x);
            in[x]++,out[y]++;
            ans+=out[x]+in[y];
        }
        v[x].clear();
        printf("%lld\n",ans);
    }
    return 0;
}


#include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <set>
int read(){
	register int x = 0;
	register char ch = getchar(), f = 1;
	for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = !f;
	for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ '0');
	return f ? x : -x;
}
#define N 100005
int n, m, q, out[N];
std :: vector<int> in[N];
long long ans;
int main(){
	n = read(), m = read();
	for (register int i = 1, u, v; i <= m; ++i){
		u = read(), v = read();
		if (u > v) std :: swap(u, v);
		in[u].push_back(v), ++out[v];
	}
	for (register int i = 1; i <= n; ++i) ans += 1ll * in[i].size() * out[i];
	printf("%lld\n", ans);
	q = read();
	for (register int i = 1; i <= q; ++i){
		int u = read();
		ans -= 1ll * in[u].size() * out[u];
		for (int v : in[u])
			ans -= 1ll * in[v].size() * out[v], in[v].push_back(u), --out[v], ans += 1ll * in[v].size() * out[v], ++out[u];
		in[u].clear();
		printf("%lld\n", ans);
	}
}


#include <iostream>
#include <vector>
#define to e[x][i]
#define w(x) (long long)in[x] * out[x]
using namespace std;
const int N = 2e5 + 2;
int n,m,q,x,in[N],out[N];
vector <int> e[N];
long long ans;
int main() {
	ios::sync_with_stdio(false);
	cin >> n >> m;
	for(int u,v,i = 1;i <= m && cin >> u >> v;in[max(u,v)]++,out[min(u,v)]++,e[min(u,v)].push_back(max(u,v)),i++);
	for(int i = 1;i <= n;ans += w(i),i++);
	cout << ans << endl;
	cin >> q;
	for(int x,i; q-- && cin >> x; e[x].clear(),cout << ans << endl)
		for(i = 0,ans -= w(x),in[x] += out[x],out[x] = 0; i < e[x].size(); ans -= w(to),e[to].push_back(x),in[to]--,out[to]++,ans += w(to),i++);
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Main implements Runnable {
    static boolean use_n_tests = false;
    static int stack_size = 1 << 27;

    void solve(FastScanner in, PrintWriter out, int testNumber) {
        int n = in.nextInt();
        long[] a = new long[n];
        Map<Long, Integer> mp = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            a[i] = in.nextLong();
            mp.merge(a[i], 1, Integer::sum);
        }
        int[] b = new int[n];
        for (int i = 0; i < b.length; i++) {
            b[i] = in.nextInt();
        }
        Set<Long> included = new HashSet<>();
        for (Long k : mp.keySet()) {
            if (mp.get(k) > 1) {
                included.add(k);
            }
        }
        for (int i = 0; i < a.length; i++) {
            if(!included.contains(a[i])) {
                for (long j : included) {
                    if ((j & a[i]) == a[i]) {
                        included.add(a[i]);
                        break;
                    }
                }
            }
        }
        long totalSum = 0;
        for (int i = 0; i < a.length; i++) {
            if (included.contains(a[i])) {
                totalSum += b[i];
            }
        }

        out.println(totalSum);

    }
// ****************************** template code ***********

    static class Range {
        int l, r;
        int id;

        public int getL() {
            return l;
        }

        public int getR() {
            return r;
        }

        public Range(int l, int r, int id) {
            this.l = l;
            this.r = r;
            this.id = id;
        }
    }

    static class Array {
        static Range[] readRanges(int n, FastScanner in) {
            Range[] result = new Range[n];
            for (int i = 0; i < n; i++) {
                result[i] = new Range(in.nextInt(), in.nextInt(), i);
            }
            return result;
        }

        static public Integer[] read(int n, FastScanner in) {
            Integer[] out = new Integer[n];
            for (int i = 0; i < out.length; i++) {
                out[i] = in.nextInt();
            }
            return out;
        }
    }

    class Graph {
        List<List<Integer>> create(int n) {
            List<List<Integer>> graph = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                graph.add(new ArrayList<>());
            }
            return graph;
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(InputStream io) {
            br = new BufferedReader(new InputStreamReader(io));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

    }

    void run_t_tests() {
        int t = in.nextInt();
        int i = 0;
        while (t-- > 0) {
            solve(in, out, i++);
        }
    }

    void run_one() {
        solve(in, out, -1);
    }

    @Override
    public void run() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);
        if (use_n_tests) {
            run_t_tests();
        } else {
            run_one();
        }
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(null, new Main(), "", stack_size);
        thread.start();
        thread.join();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class Main implements Runnable {
    static boolean use_n_tests = false;
    static int stack_size = 1 << 27;

    void solve(FastScanner in, PrintWriter out, int testNumber) {
        int n = in.nextInt();
        long[] a = new long[n];
        Map<Long, Integer> mp = new HashMap<>();
        for (int i = 0; i < a.length; i++) {
            a[i] = in.nextInt();
            mp.merge(a[i], 1, Integer::sum);
        }
        int[] b = new int[n];
        for (int i = 0; i < b.length; i++) {
            b[i] = in.nextInt();
        }
        Set<Long> included = new HashSet<>();
        for (Long k : mp.keySet()) {
            if (mp.get(k) > 1) {
                included.add(k);
            }
        }
        for (int i = 0; i < a.length; i++) {
            if(!included.contains(a[i])) {
                for (long j : included) {
                    if ((j & a[i]) == a[i]) {
                        included.add(a[i]);
                        break;
                    }
                }
            }
        }
        long totalSum = 0;
        for (int i = 0; i < a.length; i++) {
            if (included.contains(a[i])) {
                totalSum += b[i];
            }
        }

        out.println(totalSum);

    }
// ****************************** template code ***********

    static class Range {
        int l, r;
        int id;

        public int getL() {
            return l;
        }

        public int getR() {
            return r;
        }

        public Range(int l, int r, int id) {
            this.l = l;
            this.r = r;
            this.id = id;
        }
    }

    static class Array {
        static Range[] readRanges(int n, FastScanner in) {
            Range[] result = new Range[n];
            for (int i = 0; i < n; i++) {
                result[i] = new Range(in.nextInt(), in.nextInt(), i);
            }
            return result;
        }

        static public Integer[] read(int n, FastScanner in) {
            Integer[] out = new Integer[n];
            for (int i = 0; i < out.length; i++) {
                out[i] = in.nextInt();
            }
            return out;
        }
    }

    class Graph {
        List<List<Integer>> create(int n) {
            List<List<Integer>> graph = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                graph.add(new ArrayList<>());
            }
            return graph;
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(InputStream io) {
            br = new BufferedReader(new InputStreamReader(io));
        }

        public String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

    }

    void run_t_tests() {
        int t = in.nextInt();
        int i = 0;
        while (t-- > 0) {
            solve(in, out, i++);
        }
    }

    void run_one() {
        solve(in, out, -1);
    }

    @Override
    public void run() {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out);
        if (use_n_tests) {
            run_t_tests();
        } else {
            run_one();
        }
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(null, new Main(), "", stack_size);
        thread.start();
        thread.join();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.StringTokenizer;

public class Solution{

	public static void main(String[] args) {

		FastScanner fs = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);

		int tt = 1;
		while(tt-->0) {

			int n = fs.nextInt();
			long[] a = new long[n];
			for(int i=0;i<n;i++) a[i] = fs.nextLong();

			long[] b = new long[n];
			for(int i=0;i<n;i++) b[i] = fs.nextLong();

			HashMap<Long, Integer> map = new HashMap<Long, Integer>();
			ArrayList<Long> list = new ArrayList<Long>();

			for(int i=0;i<n;i++) {
				map.put(a[i], map.getOrDefault(a[i],0)+1);
			}

			for(long l : map.keySet()) {
				if(map.get(l)>1) list.add(l);
			}

			long ans = 0;
			for(int i=0;i<n;i++) {
				if(map.get(a[i])>1) ans += b[i];
				else {
					for(Long num: list) {
						if((a[i]&num)==a[i]) {
							ans += b[i];
							break;
						}
					}
				}
			}

			out.println(ans);

		}

		out.close();

	}

	static final Random random=new Random();

	static void ruffleSort(int[] a) {
		int n=a.length;//shuffle, then sort
		for (int i=0; i<n; i++) {
			int oi=random.nextInt(n), temp=a[oi];
			a[oi]=a[i]; a[i]=temp;
		}
		Arrays.sort(a);
	}

	static class FastScanner{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");

		public String next(){
			while(!st.hasMoreElements()){
				try{
					st = new StringTokenizer(br.readLine());
				} catch(IOException e){
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			return br.readLine();
		}

		public int nextInt(){
			return Integer.parseInt(next());
		}

		public int[] readArray(int n){
			int[] a = new int[n];
			for(int i=0;i<n;i++)
				a[i] = nextInt();
			return a;
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public char nextChar() {
			return next().toCharArray()[0];
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class d {
    public static void main(String[] args) throws IOException {
  //     Scanner s = new Scanner(System.in);
   BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
        //       String[] st=s.readLine().trim().split("\\s+");
        //      a[i]=Integer.parseInt(st[i]);
        //      Integer.parseInt(s.readLine().trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
       int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]);
      long[] a=new long[n];
      long[] b=new long[n];char[] [] c=new char[n][60];
      String[] st=s.readLine().trim().split("\\s+");
      String [] st1=s.readLine().trim().split("\\s+");
      for(int i=0;i<n;i++){
          a[i] = Long.parseLong(st[i]);

          c[i]=new StringBuilder(Long.toBinaryString(a[i])).reverse().toString().toCharArray();

      }
        Student[] ss=new Student[n];
        for(int i=0;i<n;i++){
            b[i] = Integer.parseInt(st1[i]);
           ss[i]=new Student(a[i],b[i],c[i]);
        }
        Arrays.sort(ss,new Sortbyroll());
        int[][] vis=new int[n][60];
        long sum=0;int[] blue=new int[n];
         long fans=0;
        for(int i=n-1;i>=0;i--){
        int flag=0;
        //    vis=new int[n][60];
            if(i<n-1){
                if(i==0){
                    if(ss[i].l!=ss[i+1].l) continue;

                }else{
                    if(ss[i].l!=ss[i+1].l){if(ss[i].l!=ss[i-1].l){ continue;}
                }}
            }else{
                if(i==0) continue;
                if(ss[i].l!=ss[i-1].l) continue;
            }    sum=ss[i].r;blue[i]=1;
            for(int k=59;k>=0;k--){
                if(k>=ss[i].x.length) continue;
                if(ss[i].x[k]=='1')     vis[i][k]=1;
            }
            for(int j=i-1;j>=0;j--){flag=0;
                if(ss[j].l==ss[j+1].l) {sum+=ss[j].r;

                for(int k=59;k>=0;k--){
                    if(k>=ss[j].x.length) continue;
                    if(ss[j].x[k]=='1')vis[j][k]=1;blue[j]=1;
                }
            //        System.out.println(ss[j].l);
                }
                else if(j>0&&ss[j].l==ss[j-1].l){ sum+=ss[j].r;
                    for(int k=59;k>=0;k--){
                        if(k>=ss[j].x.length) continue;
                       if(ss[j].x[k]=='1') vis[j][k]=1;blue[j]=1;
                    }
                //    System.out.println(ss[j].l);
                }
                else{
                    //System.out.println(ss[j].l);
                    for(int r=j+1;r<n;r++) {if(r==j||blue[r]==0) continue;
                      flag=0;
                    for(int k=59;k>=0;k--){
                        if(k>=ss[j].x.length) continue;

                        if(vis[r][k]==0&&ss[j].x[k]=='1'){
                            flag=1;break;
                        }
                    }
                    if(flag==0){
                        for(int k=59;k>=0;k--) {
                            if (k >= ss[j].x.length) continue;
                           // System.out.println(ss[r].x[k]+" "+vis[r][k]+" "+ss[r].l);
                        }
                            sum+=ss[j].r;
                        blue[j]=1;
                        for(int k=59;k>=0;k--){
                            if(k>=ss[j].x.length) continue;
                            if(ss[j].x[k]=='1')   vis[j][k]=1;
                        }break;
                    }}
                }
            }break;
        }
        System.out.println(sum);

    }
    static String lexographicallysmallest(String s) {
        if (s.length() % 2 == 1) return s;
        String s1 =lexographicallysmallest(s.substring(0, s.length()/2));
        String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length()));
        if (s1.compareTo(s2)<0) return s1 + s2;
        else return s2 + s1;
    }
    public static int countSetBits(int n)
    {
        return (BitsSetTable256[n & 0xff]
                + BitsSetTable256[(n >> 8) & 0xff]
                + BitsSetTable256[(n >> 16) & 0xff]
                + BitsSetTable256[n >> 24]);
    }
    static int[] BitsSetTable256 ;
    public static void initialize(int n)
    {
        BitsSetTable256[0] = 0;
        for (int i = 0; i <=Math.pow(2,n); i++) {
            BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
        }
    }
    static void dfs(int i,int val,ArrayList<Integer>[] adj){
    }

    static  void computeLPSArray(String pat, int M, int lps[]) {
        int len = 0;
        int i = 1;
        lps[0] = 0;
        while (i < M) {
            if (pat.charAt(i) == pat.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }
            else
            {
                if (len != 0) {
                    len = lps[len - 1];
                }
                else
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
    static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;

        if (n % 2 == 0 || n % 3 == 0) return false;

        for (int i = 5; i * i <= n; i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;

        return true;
    }
    static long powerwithmod(long  x, long y, int p) {
        long  res = 1;
        x = x % p;
        while (y > 0) {
            if ((y & 1) == 1)
                res = (res * x) % p;
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }
    static long  powerwithoutmod(long x, int y) {
        long  temp;
        if( y == 0)
            return 1;
        temp = powerwithoutmod(x, y/2);
        if (y%2 == 0)
            return temp*temp;
        else
        {
            if(y > 0)
                return x * temp * temp;
            else
                return (temp * temp) / x;
        }
    }
    static void fracion(double x) {
        String a = "" + x;
        String spilts[] = a.split("\\."); // split using decimal
        int b = spilts[1].length(); // find the decimal length
        int denominator = (int) Math.pow(10, b); // calculate the denominator
        int numerator = (int) (x * denominator); // calculate the nerumrator Ex
        // 1.2*10 = 12
        int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common
        // divisor bw them
        String fraction = "" + numerator / gcd + "/" + denominator / gcd;
        // System.out.println((denominator/gcd));
        long x1 = modInverse(denominator / gcd, 998244353);
        //  System.out.println(x1);
        System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353));
    }
    static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) {
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(i1);Queue<Integer> aq=new LinkedList<Integer>();
        aq.add(0);
        while(!q.isEmpty()){
            int i=q.poll();
            int val=aq.poll();
            if(i==n){
                return val;
            }
            if(h[i]!=null){
                for(Integer j:h[i]){
                    if(vis[j]==0){
                        q.add(j);vis[j]=1;
                        aq.add(val+1);}
                }
            }
        }return -1;
    }
    static long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    static long modInverse(long a, int m)
    {
        return (powerwithmod(a, m - 2, m));
    }
    static int MAXN;
    static int[] spf;
    static void sieve() {
        spf[1] = 1;
        for (int i=2; i<MAXN; i++)
            spf[i] = i;
        for (int i=4; i<MAXN; i+=2)
            spf[i] = 2;
        for (int i=3; i*i<MAXN; i++)
        {
            if (spf[i] == i)
            {
                for (int j=i*i; j<MAXN; j+=i)

                    if (spf[j]==j)
                        spf[j] = i;
            }
        }
    }
    static ArrayList<Integer> getFactorizationUsingSeive(int x) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        while (x != 1)
        {
            ret.add(spf[x]);
            x = x / spf[x];
        }
        return ret;
    }
   static long[] fac ;
     static void calculatefac(int mod){
         fac[0]=1;
        for (int i = 1 ;i <= MAXN; i++)
            fac[i] = fac[i-1] * i % mod;
     }
      static long nCrModPFermat(int n, int r, int mod) {
         if (r == 0)
            return 1;
        fac[0] = 1;
        return (fac[n]* modInverse(fac[r], mod)
                % mod * modInverse(fac[n-r], mod)
                                    % mod) % mod;
    } }
class Student {
    long  l;long r;char[] x;
    public Student(long l, long r,char[] x) {
        this.l = l;
        this.r = r;this.x=x;
    }

    public String toString()
    {
        return this.l+" ";
    }
}
class Sortbyroll implements Comparator<Student>
{

    public int compare(Student a, Student b){
      if(a.l<b.l) return -1;
      else if(a.l==b.l){
          if(a.r==b.r){
              return 0;
          }
          if(a.r<b.r) return -1;
          return 1;}
      return 1;  }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class d {
    public static void main(String[] args) throws IOException {
  //     Scanner s = new Scanner(System.in);
   BufferedReader s=new BufferedReader(new InputStreamReader(System.in));
        //       String[] st=s.readLine().trim().split("\\s+");
        //      a[i]=Integer.parseInt(st[i]);
        //      Integer.parseInt(s.readLine().trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
       int n=Integer.parseInt(s.readLine().trim().split("\\s+")[0]);
      long[] a=new long[n];
      long[] b=new long[n];char[] [] c=new char[n][60];
      String[] st=s.readLine().trim().split("\\s+");
      String [] st1=s.readLine().trim().split("\\s+");
      for(int i=0;i<n;i++){
          a[i] = Long.parseLong(st[i]);

          c[i]=new StringBuilder(Long.toBinaryString(a[i])).reverse().toString().toCharArray();

      }
        Student[] ss=new Student[n];
        for(int i=0;i<n;i++){
            b[i] = Integer.parseInt(st1[i]);
           ss[i]=new Student(a[i],b[i],c[i]);
        }
        Arrays.sort(ss,new Sortbyroll());
        int[] vis=new int[60];
        long sum=0;
         long fans=0;
        for(int i=n-1;i>=0;i--){
        int flag=0;
            vis=new int[60];
            if(i<n-1){
                if(i==0){
                    if(ss[i].l!=ss[i+1].l) continue;

                }else{
                    if(ss[i].l!=ss[i+1].l){if(ss[i].l!=ss[i-1].l){ continue;}
                }}
            }else{
                if(i==0) continue;
                if(ss[i].l!=ss[i-1].l) continue;
            }    sum=ss[i].r;
            for(int k=59;k>=0;k--){
                if(k>=ss[i].x.length) continue;
                vis[k]=1;
            }
            for(int j=i-1;j>=0;j--){flag=0;
                if(ss[j].l==ss[j+1].l) {sum+=ss[j].r;

                for(int k=59;k>=0;k--){
                    if(k>=ss[j].x.length) continue;
                    vis[k]=1;
                }
                }
                else if(j>0&&ss[j].l==ss[j-1].l){ sum+=ss[j].r;
                    for(int k=59;k>=0;k--){
                        if(k>=ss[j].x.length) continue;
                        vis[k]=1;
                    }
                }
                else{
                    for(int k=59;k>=0;k--){
                        if(k>=ss[j].x.length) continue;

                        if(vis[k]==0&&ss[j].x[k]=='1'){
                            flag=1;break;
                        }
                    }if(flag==0){
                        sum+=ss[j].r;
                        for(int k=59;k>=0;k--){
                            if(k>=ss[j].x.length) continue;
                            vis[k]=1;
                        }
                    }
                }
            }break;
        }
        System.out.println(sum);

    }
    static String lexographicallysmallest(String s) {
        if (s.length() % 2 == 1) return s;
        String s1 =lexographicallysmallest(s.substring(0, s.length()/2));
        String s2 = lexographicallysmallest(s.substring(s.length()/2, s.length()));
        if (s1.compareTo(s2)<0) return s1 + s2;
        else return s2 + s1;
    }
    public static int countSetBits(int n)
    {
        return (BitsSetTable256[n & 0xff]
                + BitsSetTable256[(n >> 8) & 0xff]
                + BitsSetTable256[(n >> 16) & 0xff]
                + BitsSetTable256[n >> 24]);
    }
    static int[] BitsSetTable256 ;
    public static void initialize(int n)
    {
        BitsSetTable256[0] = 0;
        for (int i = 0; i <=Math.pow(2,n); i++) {
            BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
        }
    }
    static void dfs(int i,int val,ArrayList<Integer>[] adj){
    }

    static  void computeLPSArray(String pat, int M, int lps[]) {
        int len = 0;
        int i = 1;
        lps[0] = 0;
        while (i < M) {
            if (pat.charAt(i) == pat.charAt(len)) {
                len++;
                lps[i] = len;
                i++;
            }
            else
            {
                if (len != 0) {
                    len = lps[len - 1];
                }
                else
                {
                    lps[i] = len;
                    i++;
                }
            }
        }
    }
    static boolean isPrime(int n) {
        if (n <= 1) return false;
        if (n <= 3) return true;

        if (n % 2 == 0 || n % 3 == 0) return false;

        for (int i = 5; i * i <= n; i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;

        return true;
    }
    static long powerwithmod(long  x, long y, int p) {
        long  res = 1;
        x = x % p;
        while (y > 0) {
            if ((y & 1) == 1)
                res = (res * x) % p;
            y = y >> 1;
            x = (x * x) % p;
        }
        return res;
    }
    static long  powerwithoutmod(long x, int y) {
        long  temp;
        if( y == 0)
            return 1;
        temp = powerwithoutmod(x, y/2);
        if (y%2 == 0)
            return temp*temp;
        else
        {
            if(y > 0)
                return x * temp * temp;
            else
                return (temp * temp) / x;
        }
    }
    static void fracion(double x) {
        String a = "" + x;
        String spilts[] = a.split("\\."); // split using decimal
        int b = spilts[1].length(); // find the decimal length
        int denominator = (int) Math.pow(10, b); // calculate the denominator
        int numerator = (int) (x * denominator); // calculate the nerumrator Ex
        // 1.2*10 = 12
        int gcd = (int) gcd((long) numerator, denominator); // Find the greatest common
        // divisor bw them
        String fraction = "" + numerator / gcd + "/" + denominator / gcd;
        // System.out.println((denominator/gcd));
        long x1 = modInverse(denominator / gcd, 998244353);
        //  System.out.println(x1);
        System.out.println((((numerator / gcd) % 998244353 * (x1 % 998244353)) % 998244353));
    }
    static int bfs(int i1, ArrayList<Integer>[] h, int[] vis, int n,int val1) {
        Queue<Integer> q = new LinkedList<Integer>();
        q.add(i1);Queue<Integer> aq=new LinkedList<Integer>();
        aq.add(0);
        while(!q.isEmpty()){
            int i=q.poll();
            int val=aq.poll();
            if(i==n){
                return val;
            }
            if(h[i]!=null){
                for(Integer j:h[i]){
                    if(vis[j]==0){
                        q.add(j);vis[j]=1;
                        aq.add(val+1);}
                }
            }
        }return -1;
    }
    static long gcd(long a, long b) {
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
    static long modInverse(long a, int m)
    {
        return (powerwithmod(a, m - 2, m));
    }
    static int MAXN;
    static int[] spf;
    static void sieve() {
        spf[1] = 1;
        for (int i=2; i<MAXN; i++)
            spf[i] = i;
        for (int i=4; i<MAXN; i+=2)
            spf[i] = 2;
        for (int i=3; i*i<MAXN; i++)
        {
            if (spf[i] == i)
            {
                for (int j=i*i; j<MAXN; j+=i)

                    if (spf[j]==j)
                        spf[j] = i;
            }
        }
    }
    static ArrayList<Integer> getFactorizationUsingSeive(int x) {
        ArrayList<Integer> ret = new ArrayList<Integer>();
        while (x != 1)
        {
            ret.add(spf[x]);
            x = x / spf[x];
        }
        return ret;
    }
   static long[] fac ;
     static void calculatefac(int mod){
         fac[0]=1;
        for (int i = 1 ;i <= MAXN; i++)
            fac[i] = fac[i-1] * i % mod;
     }
      static long nCrModPFermat(int n, int r, int mod) {
         if (r == 0)
            return 1;
        fac[0] = 1;
        return (fac[n]* modInverse(fac[r], mod)
                % mod * modInverse(fac[n-r], mod)
                                    % mod) % mod;
    } }
class Student {
    long  l;long r;char[] x;
    public Student(long l, long r,char[] x) {
        this.l = l;
        this.r = r;this.x=x;
    }

    public String toString()
    {
        return this.l+" ";
    }
}
class Sortbyroll implements Comparator<Student>
{

    public int compare(Student a, Student b){
      if(a.l<b.l) return -1;
      else if(a.l==b.l){
          if(a.r==b.r){
              return 0;
          }
          if(a.r<b.r) return -1;
          return 1;}
      return 1;  }
}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define M 1000000007
#define INF ((1LL<<62LL) - 1)

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n; cin >> n;
    int a[n];
    int b[n];

    for(int i=0;i<n;i++) cin >> a[i];
    for(int i=0;i<n;i++) cin >> b[i];

    // cnt map will store the number of student with a particular set of skills.
    // if value is >=2 then take it without any check. Why?
    // because he won't be the only one who thinks he's better than others.
    // if value is 1, then we'll check -
    // "the skills possessed by this guy are already possessed by some chosen guy or not?"
    // for that we can take OR of all the chosen students' skills
    map<int,int> cnt;
    for(int i=0;i<n;i++){
        cnt[a[i]]++;
    }

    // Okay. I misunderstood something. One student can be better than other in one skill
    // and better than another in second skill. This also counts to the logic that he is better than everyone else.
    // So, now one has to have a skillset which doesn't skillset of atleast one of the chosen student.
    int ans = 0;
    for(int i=0;i<n;i++){
        if(cnt[a[i]]>=2){
            ans+=b[i];
        }
    }

    for(int i=0;i<n;i++){
        if(cnt[a[i]]==1){
            bool flag = false;
            for(pair<int,int> p:cnt) {
                if(p.second>=2) {
                    int chosen = p.first;
                    bool tempFlag = true;
                    for (int j = 0; j < 60; j++) {
                        if ((((a[i] >> j) & 1) == 1) && (((chosen >> j) & 1) == 0)) {
                            tempFlag = false;
                            break;
                        }
                    }
                    if (tempFlag) {
                        flag = true;
                        break;
                    }
                }
            }
            if(flag){
                ans+=b[i];
            }
        }
    }

    cout << ((n==1)?0:ans) << "\n";

}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define M 1000000007
#define INF ((1LL<<62LL) - 1)

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n; cin >> n;
    int a[n];
    int b[n];

    for(int i=0;i<n;i++) cin >> a[i];
    for(int i=0;i<n;i++) cin >> b[i];

    // cnt map will store the number of student with a particular set of skills.
    // if value is >=2 then take it without any check. Why?
    // because he won't be the only one who thinks he's better than others.
    // if value is 1, then we'll check -
    // "the skills possessed by this guy are already possessed by some chosen guy or not?"
    // for that we can take OR of all the chosen students' skills
    map<int,int> cnt;
    for(int i=0;i<n;i++){
        cnt[a[i]]++;
    }

    // Okay. I misunderstood something. One student can be better than other in one skill
    // and better than another in second skill. This also counts to the logic that he is better than everyone else.
    // So, now one has to have a skillset which doesn't skillset of atleast one of the chosen student.
    int ans = 0;
    for(int i=0;i<n;i++){
        if(cnt[a[i]]>=2){
            ans+=b[i];
        }
    }

    for(int i=0;i<n;i++){
        if(cnt[a[i]]==1){
            bool flag = false;
            for(int k=0;k<n;k++) {
                if(cnt[a[k]]>=2) {
                    bool tempFlag = true;
                    for (int j = 0; j < 60; j++) {
                        if ((((a[i] >> j) & 1) == 1) && (((a[k] >> j) & 1) == 0)) {
                            tempFlag = false;
                            break;
                        }
                    }
                    if (tempFlag) {
                        flag = true;
                        break;
                    }
                }
            }
            if(flag){
                ans+=b[i];
            }
        }
    }

    cout << ((n==1)?0:ans) << "\n";

}


#include<bits/stdc++.h>
using namespace std;
#define int long long
#define M 1000000007
#define INF ((1LL<<62LL) - 1)

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n; cin >> n;
    int a[n];
    int b[n];

    for(int i=0;i<n;i++) cin >> a[i];
    for(int i=0;i<n;i++) cin >> b[i];

    // cnt map will store the number of student with a particular set of skills.
    // if value is >=2 then take it without any check. Why?
    // because he won't be the only one who thinks he's better than others.
    // if value is 1, then we'll check -
    // "the skills possessed by this guy are already possessed by some chosen guy or not?"
    // for that we can take OR of all the chosen students' skills
    map<int,int> cnt;
    for(int i=0;i<n;i++){
        cnt[a[i]]++;
    }

    int SKILL_SET = 0;
    int ans = 0;
    for(int i=0;i<n;i++){
        if(cnt[a[i]]>=2){
            SKILL_SET|=a[i];
            ans+=b[i];
        }
    }

    for(int i=0;i<n;i++){
        if(cnt[a[i]]==1){
            bool flag = true;
            for(int j=0;j<60;j++){
                if((((a[i]>>j)&1) == 1) && (((SKILL_SET>>j)&1) == 0)){
                    flag = false;
                }
            }
            if(flag){
                ans+=b[i];
            }
        }
    }

    cout << ((n==1)?0:ans) << "\n";

}


#include <bits/stdc++.h>
#define forn(i,n) for(int i=0; i<n; i++)
#define pb push_back
#define ll long long int
#define sz(arr) (int)arr.size()

using namespace std;

int main(){
    int n;
    cin>>n;
    vector<ll> a(n);
    vector<ll> b(n);
    vector<bool> used(n);
    map<ll,vector<int> > arr;
    forn(i,n) cin>>a[i];
    forn(i,n) cin>>b[i];
    forn(i,n) arr[a[i]].pb(i);

    ll ans=0;
    auto it=arr.begin();
    for(it=arr.begin(); it!=arr.end(); it++){
        if (sz(it->second)>=2){
            ll mask=it->first;
            ll store=0;
            forn(i,n){
                ll comp=(~mask)&((1<<60)-1);
                if ((comp&a[i])==0){
                    store+=b[i];
                }
            }
            ans=max(ans,store);

        }
    }
    cout<<ans;
}


#include <bits/stdc++.h>
#define forn(i,n) for(int i=0; i<n; i++)
#define pb push_back
#define ll long long int
#define sz(arr) (int)arr.size()

using namespace std;

int main(){
    int n;
    cin>>n;
    vector<ll> a(n);
    vector<ll> b(n);
    vector<bool> used(n);
    map<ll,vector<int> > arr;
    forn(i,n) cin>>a[i];
    forn(i,n) cin>>b[i];
    forn(i,n) arr[a[i]].pb(i);

    auto it=arr.begin();
    vector<ll> valid;
    for(it=arr.begin(); it!=arr.end(); it++){
        if (sz(it->second)>=2){
            valid.pb(it->first);
            ll mask=it->first;
            ll store=0;

        }
    }

    ll ans=0;
    forn(i,n){
        forn(j,sz(valid)){
            ll mask=valid[j];ll one=1;
            ll comp=(~mask)&((one<<60)-1);
            if ((comp&a[i])==0){
                ans+=b[i];
                break;
            }
        }
    }
    cout<<ans;
}


#include <bits/stdc++.h>
#define forn(i,n) for(int i=0; i<n; i++)
#define pb push_back
#define ll long long int
#define sz(arr) (int)arr.size()

using namespace std;

int main(){
    int n;
    cin>>n;
    vector<ll> a(n);
    vector<ll> b(n);
    vector<bool> used(n);
    map<ll,vector<int> > arr;
    forn(i,n) cin>>a[i];
    forn(i,n) cin>>b[i];
    forn(i,n) arr[a[i]].pb(i);

    ll ans=0;
    auto it=arr.begin();
    for(it=arr.begin(); it!=arr.end(); it++){
        if (sz(it->second)>=2){
            ll mask=it->first;
            ll store=0;
            forn(i,n){
                ll one=1;
                ll comp=(~mask)&((one<<60)-1);
                if ((comp&a[i])==0){
                    store+=b[i];
                }
            }
            ans=max(ans,store);

        }
    }
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 int tot=0;
 for(auto k:ma)
 {
     if(k.y>1)
     {
         tot=tot|k.x;
     }

 }

 for(auto k:ma)
 {
     if(tot|k.x==tot)
     {
         ans+=mt[k.x];
     }
 }
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 int tot=0;
 if(n==1)
 {
     cout<<0;
     return 0;
 }
 for(auto k:ma)
 {
     if(k.y>1)
     {
         debug(k.x);
         tot=tot|k.x;
         debug(tot);
     }

 }

 for(auto k:ma)
 {
     if((tot|k.x)==tot)
     {
         debug(k.x);
         ans+=mt[k.x];
         debug(ans);
     }
 }
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 int tot=0;
 if(n==1)
 {
     cout<<0;
     return 0;
 }
 for(auto k:ma)
 {
     if(k.y>1)
     {
        // debug(k.x);
         tot=tot|k.x;
         //debug(tot);
     }

 }

 for(auto k:ma)
 {
     if((tot|k.x)==tot)
     {
        // debug(k.x);
         ans+=mt[k.x];
        // debug(ans);
     }
 }
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 set<int> s;
 for(auto k:ma)
 {
    // debug(k.x);
     if(k.y>1)
     {

         int temp=0;
         for(auto kk:ma)
         {
          //   debug(kk.x|k.x);
             if((kk.x|k.x)==k.x)
             {
                s.insert(kk.x);
             }
         }

     }
 }
 for(int k:s)
 ans+=mt[k];
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 int tot=0;
 for(auto k:ma)
 {
     if(k.y>1)
     {
         tot=tot|k.x;
     }

 }

 for(auto k:ma)
 {
     if((tot|k.x)==tot)
     {

         ans+=mt[k.x];
     }
 }
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define int         long long
#define float       long double
#define pb          push_back
#define ld          long double
#define f(i,a,b)    for(int i=a;i<b;i++)
#define mp          make_pair
#define pii         pair<int,int>
#define vi          vector<int>
#define vpi         vector<pair<int,int> >
#define mii         map<int,int>
#define all(a)      (a).begin(),(a).end()
#define debug(x)    cout<<#x<<" is "<<(x)<<endl
#define mp          make_pair
#define x           first
#define y           second
#define pb          push_back
#define endl        '\n'
#define si(x)       (int((x).size()))
#define IOS         ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define txt         freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int inf=99999999999;
const int mod=998244353 ;
void inp(int *arr,int n)
{
    for(int i=0;i<n;i++) cin>>arr[i];
}
bool fun(pair<int,int> p1,pair<int,int> p2)
{
    if(p1.x==p2.x)
        return p1.y<p2.y;
    else return p1.x>p2.x;
}
int solve()
{
 int n;
 cin>>n;
 int a[n];
 mii ma;
 mii mt;
 f(i,0,n)
 {

     cin>>a[i];
     ma[a[i]]++;
 }
 f(i,0,n)
 {
     int b;
     cin>>b;
     mt[a[i]]+=b;
 }
 int ans=0;
 for(auto k:ma)
 {
    // debug(k.x);
     if(k.y>1)
     {

         int temp=0;
         for(auto kk:ma)
         {
          //   debug(kk.x|k.x);
             if((kk.x|k.x)==k.x)
             {
                 temp+=mt[kk.x];
             }
         }
         ans=max(ans,temp);
     }
 }
 cout<<ans;
}
main()
{

    IOS;
//    int t;
//    cin>>t;
//    while(t--)
    solve();
    return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define loop(i,a,n) for(ll i=a;i<n;++i)
#define revloop(i,a,b) for(ll i=a;i>=b;--i)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define INF 99999999999999
#define MOD 1000000007

void func()
{
    ll n;
    cin>>n;
    ll a[n],b[n];
    map<ll,ll> m;
    set<ll> s;
    vector<ll> ans;
    for(ll i=0;i<n;i++){
        cin>>a[i];
        m[a[i]]++;
    }
    for(ll i=0;i<n;i++){
        cin>>b[i];
    }
    for(ll i=0;i<n;i++){
        if(m[a[i]]>=2){
            ans.pb(i);
            s.insert(a[i]);
        }
    }
    for(ll i=0;i<n;i++){
        if(m[a[i]]==1){
            for(auto u : s){
                ll t=u|a[i];
                if(t==u){
                    ans.pb(i);
                    s.insert(a[i]);
                    break;
                }
            }
        }
    }
    ll sum=0;
    if(ans.size()>=2){
        for(ll i=0;i<ans.size();i++){
            sum+=b[ans[i]];
        }
    }
    cout<<sum<<"\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w" , stdout);
    #endif

    ll t=1;
    //cin>>t;
    while(t--)
    {
        func();
    }

}


#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define loop(i,a,n) for(ll i=a;i<n;++i)
#define revloop(i,a,b) for(ll i=a;i>=b;--i)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define INF 99999999999999
#define MOD 1000000007

void func()
{
    ll n;
    cin>>n;
    ll a[n],b[n];
    map<ll,ll> m;
    set<ll> s;
    vector<ll> ans;
    for(ll i=0;i<n;i++){
        cin>>a[i];
        m[a[i]]++;
    }
    for(ll i=0;i<n;i++){
        cin>>b[i];
    }
    for(ll i=0;i<n;i++){
        if(m[a[i]]>=2){
            ans.pb(i);
            s.insert(a[i]);
        }
    }
    for(ll i=0;i<n;i++){
        if(m[a[i]]==1){
            bool flag=true;
            for(auto u : s){
                ll t=u|a[i];
                if(t!=u){
                    flag=false;
                    break;
                }
            }
            if(flag){
                ans.pb(i);
                s.insert(a[i]);
            }
        }
    }
    ll sum=0;
    if(ans.size()>=2){
        for(ll i=0;i<ans.size();i++){
            sum+=b[ans[i]];
        }
    }
    cout<<sum<<"\n";
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r" , stdin);
    freopen("output.txt", "w" , stdout);
    #endif

    ll t=1;
    //cin>>t;
    while(t--)
    {
        func();
    }

}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int compare(int a,int b){
    while(a>0 && b>0){
        if(a%2 > b%2){return 0;}
        a>>=1;b>>=1;
    }
    return 1;

}

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    //freopen("write.txt","w",stdout);
    #endif //ONLINE_JUDGE

    int n;cin>>n;
    ll arr[7005];
    map<ll,ll>::iterator iter;
    vector<int> bits;
    map<ll,ll> values;

    int con=0;

    for(int i=0;i<n;i++){cin>>arr[i];}
    for(int i=0;i<n;i++){
        int x = arr[i];
        int k;cin>>k;

        if(values[x]!=0){
            con=1;
            bits.push_back(x);
            /*
            int counter=0;
            while(x>0){
                if(x%2==1){bits[counter]=1; }
                counter++;
                x>>=1;
            }
            */

        }
        values[x]+=k;

    }

    if(con==0){cout<<0<<endl;return 0;}

    sort(bits.begin(),bits.end());
    vector<int>::iterator ip = unique(bits.begin(),bits.end());
    bits.resize(distance(bits.begin(), ip));

    int ans=0;
    for(iter=values.begin();iter!=values.end();iter++){
        int x = iter->first,v = iter->second;
        int counter=0;

        for(int i=(int)bits.size()-1;i>=0;i--){
            if(x>bits[i]){break;}
            if(compare(x,bits[i])){ans+=values[x];break;}
        }

    }

    cout<<ans<<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int compare(ll a,ll b){
    while(a>0 && b>0){
        if(a%2 > b%2){return 0;}
        a>>=1;b>>=1;
    }
    return 1;

}

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    //freopen("write.txt","w",stdout);
    #endif //ONLINE_JUDGE

    int n;cin>>n;
    ll arr[7005];
    map<ll,ll>::iterator iter;
    vector<ll> bits;
    map<ll,ll> values;

    int con=0;

    for(int i=0;i<n;i++){cin>>arr[i];}
    for(int i=0;i<n;i++){
        ll x = arr[i];
        ll k;cin>>k;

        if(values[x]!=0){
            con=1;
            bits.push_back(x);

        }
        values[x]+=k;

    }

    if(con==0){cout<<0<<endl;return 0;}

    sort(bits.begin(),bits.end());
    vector<ll>::iterator ip = unique(bits.begin(),bits.end());
    bits.resize(distance(bits.begin(), ip));

    ll ans=0;
    for(iter=values.begin();iter!=values.end();iter++){
        ll x = iter->first,v = iter->second;
        int counter=0;

        for(int i=(int)bits.size()-1;i>=0;i--){
            if(x>bits[i]){break;}
            if(compare(x,bits[i])){ans+=values[x];break;}
        }

    }

    cout<<ans<<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    //freopen("write.txt","w",stdout);
    #endif //ONLINE_JUDGE

    int n;cin>>n;
    ll arr[7005];
    map<ll,ll>::iterator iter;
    vector<int> bits(65);
    map<ll,ll> values;

    int con=0;

    for(int i=0;i<n;i++){cin>>arr[i];}
    for(int i=0;i<n;i++){
        int x = arr[i];
        int k;cin>>k;

        if(values[x]!=0){
            con=1;
            int counter=0;
            while(x>0){
                if(x%2==1){bits[counter]=1; }
                counter++;
                x>>=1;
            }
        }
        values[arr[i]]+=k;

    }

    if(con==0){cout<<0<<endl;return 0;}

    int ans=0;
    for(iter=values.begin();iter!=values.end();iter++){
        int x = iter->first,v = iter->second;
        int counter=0;
        while(x>0){
            if(x%2 > bits[counter]){x=-1;break;}
            counter++;
            x>>=1;
        }
        if(x!=-1){ans+=v;}
    }

    cout<<ans<<endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int main(){
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    #ifndef ONLINE_JUDGE
    freopen("read.txt","r",stdin);
    //freopen("write.txt","w",stdout);
    #endif //ONLINE_JUDGE

    int n;cin>>n;
    ll arr[7005];
    map<ll,ll>::iterator iter;
    vector<int> bits(65);
    map<ll,ll> values;

    for(int i=0;i<n;i++){cin>>arr[i];}
    for(int i=0;i<n;i++){
        int x = arr[i];
        int k;cin>>k;

        if(values[x]!=0){
            int counter=0;
            while(x>0){
                if(x%2==1){bits[counter]=1; }
                counter++;
                x>>=1;
            }
        }
        values[arr[i]]+=k;

    }
    int ans=0;
    for(iter=values.begin();iter!=values.end();iter++){
        int x = iter->first,v = iter->second;
        if(x==0){continue;}
        int counter=0;
        while(x>0){
            if(x%2 > bits[counter]){x=-1;break;}
            counter++;
            x>>=1;
        }
        if(x!=-1){ans+=v;}
    }

    cout<<ans<<endl;

    /*
    for(int i=0;i<n;i++){
        ll x = arr[i];
        int counter=0;
        while(x>0){
            if(x%2==1){v[counter][ arr[i] ]++; }
            counter++;
            x>>=1;
        }
    }

    while(1){
        vector<ll> finished;
        for(int i=60;i>=0;i--){
            int s = (int)v[i].size();
            if(s==1){
                iter=v[i].begin();
                if(iter->second ==1){finished.push_back(iter->first);}
            }
        }
        if((int)finished.size()==0){break;}

        for(int i=0;i<finished.size();i++){
            ll x = finished[i];
            int counter=0;
            while(x>0){
                if(x%2==1){v[counter].erase(finished[i]); }
                counter++;
                x>>=1;
            }
        }

    }

    ll ans=0;
    for(int i=0;i<=60;i++){
        for(iter=v[i].begin();iter!=v[i].end();iter++){
            ans+=values[iter->first];
            values[iter->first]=0;
        }
    }
    cout<<ans<<endl;

*/

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

# define int long long
typedef unsigned long long ul ;
typedef long long ll ;
typedef string str ;
typedef pair <int, int >  pii ;
typedef pair <ll, ll>  pll ;
typedef vector <int> vi ;
typedef vector <bool> vb ;
typedef vector <ll> vll ;
typedef vector <pii> vpi ;
typedef vector <pll> vpl ;
#define umap unordered_map

#define MOD 1000000007
#define vec vector
#define nl '\n' << flush
#define is ==
#define all(v) (v).begin() , (v).end()
#define revall(v) (v).rbegin() , (v).rend()
#define sumof(v) accumulate(all(v), 0LL, plus<ll>())
#define maxof(v) max_element(all(v))
#define minof(v) min_element(all(v))
#define rev(v) reverse(all(v))
#define sz(v)  (long long)(v).size()
#define forn(i, n) for ( ll i = 0 ; i < (n) ; i++ )
#define fornr(i, n) for ( ll i = (n)-1 ; i >= 0 ; i-- )
#define forit(it, c) for ( auto it = (c).begin(); it != (c).end(); it++)
#define range(i, l, r) for ( ll i = (l) ; i < (r) ; i++ )
#define ranger(i, r,l) for ( ll i = (r) ; i >= (l) ; i-- )
#define lp(i, n) for ( ll i = 0 ; i < (n) ; i++ )
#define lpd(i, n) for ( ll i = (n)-1 ; i >= 0 ; i-- )
#define lpc(it, c) for ( auto it = (c).begin(); it != (c).end(); it++)
#define lpv(val, c) for ( auto val : c )
#define lpr(i, l, r) for ( ll i = (l) ; i < (r) ; i++ )
#define lpdr(i, l, r) for ( ll i = (r)-1 ; i >= (l) ; i-- )

#define F first
#define S second
#define pb push_back
#define eb emplace_back
#define inf INT_MAX
#define eps 1e-6
#define PI acos(-1)

#define tc(t) ul testcases ; cin >> testcases ; for(int testcase = 1 ; testcase <= testcases ; testcase++)
#define prntc cout << "Case #" << testcase << ": ";
#define printvec(c) for (auto it = (c).begin(); it != --((c).end()); it++) cout << *it << " "; cout << *(c.rbegin()) << "\n" << flush
#define printnl(v) cout << v << "\n" << flush
#define invec(vec_name, vec_size) vll vec_name(vec_size); lp(i,vec_size) cin >> vec_name[i];
#define printsp(x) cout<< x<< " "
#define fast ios::sync_with_stdio(false); cin.tie(0);

#ifndef ONLINE_JUDGE
#define show ; cerr <<
#define sp ; cerr << "\n";
#define debug(ds_name) for ( auto val : ds_name ) cerr<<val<<"\n" ; cerr<<"\n";
#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__);
string sep = "-----------------------------\n";
#else
#define show ; {}
#define sp ; {} ;
#define debug(ds_name) {} ;
#define pr(...) {} ;
string sep = "" ;
#endif
template <class T> ostream &operator <<(ostream &os, const vector<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const unordered_set<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const set<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const multiset<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class S, class T> ostream &operator <<(ostream &os, const pair<S, T> &p) {return os << "(" << p.first << ", " << p.second << ")"; } template <class S, class T> ostream &operator <<(ostream &os, const unordered_map<S, T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class S, class T> ostream &operator <<(ostream &os, const map<S, T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n"; } template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ", "; dbs(str.substr(idx + 1), s...); } template <class T> T mx(T t) {return t; } template <class T, class... S> T mx(T t, S... s) {T tt = mx(s...); return (t) > (tt) ? (t) : (tt); } template <class T> T mn(T t) {return t; } template <class T, class... S> T mn(T t, S... s) {T tt = mn(s...); return (t) < (tt) ? (t) : (tt); } template <class T, class Op> T acc(Op op, T t) {return t; } template <class T, class Op, class... S> T acc(Op op, T t, S... s) {return op(t, acc(op, s...)); } template <class D1, class D2> auto lambdamax() {return [](D1 a, D2 b) {return (a) > (b) ? (a) : (b) ; } ; } template <class D1, class D2> auto lambdamin() {return [](D1 a, D2 b) {return (a) < (b) ? (a) : (b) ; } ; } ll modExp(ll x, ll y, ll mod) {x %= mod, y %= (mod - 1) ; ll res = 1; while (y) {if (y & 1) res = (res * x) % mod; y /= 2, x = (x * x) % mod; } return res % mod; }

int32_t main()
{
    fast
    #ifndef ONLINE_JUDGE
        freopen("./input.txt", "r", stdin);
    #endif
    int n;
    cin>>n;
    invec(a, n);
    invec(b, n);
    vec<vi> m(60);
    umap<int,int> f;
    set<int> s, x;
    forn(i,n)
    {
        f[a[i]]++;
        if(f[a[i]]>=2)
            s.insert(a[i]);
    }
    forn(i,n)
    {
        if(s.find(a[i])==s.end())
        {
            for(int el : s)
            {
                if((el|a[i])==el)
                {
                    x.insert(a[i]);
                    break;
                }
            }
        }
    }
    int sum = 0;
    forn(i,n)
    {
        if(s.find(a[i])!=s.end() or x.find(a[i])!=x.end())
        {
            sum+=b[i];
        }
    }
    cout<<sum<<endl;

}


#include <bits/stdc++.h>
using namespace std;

# define int long long
typedef unsigned long long ul ;
typedef long long ll ;
typedef string str ;
typedef pair <int, int >  pii ;
typedef pair <ll, ll>  pll ;
typedef vector <int> vi ;
typedef vector <bool> vb ;
typedef vector <ll> vll ;
typedef vector <pii> vpi ;
typedef vector <pll> vpl ;
#define umap unordered_map

#define MOD 1000000007
#define vec vector
#define nl '\n' << flush
#define is ==
#define all(v) (v).begin() , (v).end()
#define revall(v) (v).rbegin() , (v).rend()
#define sumof(v) accumulate(all(v), 0LL, plus<ll>())
#define maxof(v) max_element(all(v))
#define minof(v) min_element(all(v))
#define rev(v) reverse(all(v))
#define sz(v)  (long long)(v).size()
#define forn(i, n) for ( ll i = 0 ; i < (n) ; i++ )
#define fornr(i, n) for ( ll i = (n)-1 ; i >= 0 ; i-- )
#define forit(it, c) for ( auto it = (c).begin(); it != (c).end(); it++)
#define range(i, l, r) for ( ll i = (l) ; i < (r) ; i++ )
#define ranger(i, r,l) for ( ll i = (r) ; i >= (l) ; i-- )
#define lp(i, n) for ( ll i = 0 ; i < (n) ; i++ )
#define lpd(i, n) for ( ll i = (n)-1 ; i >= 0 ; i-- )
#define lpc(it, c) for ( auto it = (c).begin(); it != (c).end(); it++)
#define lpv(val, c) for ( auto val : c )
#define lpr(i, l, r) for ( ll i = (l) ; i < (r) ; i++ )
#define lpdr(i, l, r) for ( ll i = (r)-1 ; i >= (l) ; i-- )

#define F first
#define S second
#define pb push_back
#define eb emplace_back
#define inf INT_MAX
#define eps 1e-6
#define PI acos(-1)

#define tc(t) ul testcases ; cin >> testcases ; for(int testcase = 1 ; testcase <= testcases ; testcase++)
#define prntc cout << "Case #" << testcase << ": ";
#define printvec(c) for (auto it = (c).begin(); it != --((c).end()); it++) cout << *it << " "; cout << *(c.rbegin()) << "\n" << flush
#define printnl(v) cout << v << "\n" << flush
#define invec(vec_name, vec_size) vll vec_name(vec_size); lp(i,vec_size) cin >> vec_name[i];
#define printsp(x) cout<< x<< " "
#define fast ios::sync_with_stdio(false); cin.tie(0);

#ifndef ONLINE_JUDGE
#define show ; cerr <<
#define sp ; cerr << "\n";
#define debug(ds_name) for ( auto val : ds_name ) cerr<<val<<"\n" ; cerr<<"\n";
#define pr(...) dbs(#__VA_ARGS__, __VA_ARGS__);
string sep = "-----------------------------\n";
#else
#define show ; {}
#define sp ; {} ;
#define debug(ds_name) {} ;
#define pr(...) {} ;
string sep = "" ;
#endif
template <class T> ostream &operator <<(ostream &os, const vector<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const unordered_set<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const set<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> ostream &operator <<(ostream &os, const multiset<T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class S, class T> ostream &operator <<(ostream &os, const pair<S, T> &p) {return os << "(" << p.first << ", " << p.second << ")"; } template <class S, class T> ostream &operator <<(ostream &os, const unordered_map<S, T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class S, class T> ostream &operator <<(ostream &os, const map<S, T> &p) {os << "[ "; for (auto &it : p) os << it << " "; return os << "]"; } template <class T> void dbs(string str, T t) {cerr << str << " : " << t << "\n"; } template <class T, class... S> void dbs(string str, T t, S... s) {int idx = str.find(','); cerr << str.substr(0, idx) << " : " << t << ", "; dbs(str.substr(idx + 1), s...); } template <class T> T mx(T t) {return t; } template <class T, class... S> T mx(T t, S... s) {T tt = mx(s...); return (t) > (tt) ? (t) : (tt); } template <class T> T mn(T t) {return t; } template <class T, class... S> T mn(T t, S... s) {T tt = mn(s...); return (t) < (tt) ? (t) : (tt); } template <class T, class Op> T acc(Op op, T t) {return t; } template <class T, class Op, class... S> T acc(Op op, T t, S... s) {return op(t, acc(op, s...)); } template <class D1, class D2> auto lambdamax() {return [](D1 a, D2 b) {return (a) > (b) ? (a) : (b) ; } ; } template <class D1, class D2> auto lambdamin() {return [](D1 a, D2 b) {return (a) < (b) ? (a) : (b) ; } ; } ll modExp(ll x, ll y, ll mod) {x %= mod, y %= (mod - 1) ; ll res = 1; while (y) {if (y & 1) res = (res * x) % mod; y /= 2, x = (x * x) % mod; } return res % mod; }

int32_t main()
{
    fast
    #ifndef ONLINE_JUDGE
        freopen("./input.txt", "r", stdin);
    #endif
    int n;
    cin>>n;
    vec<vi> g(n+1);
    for(int i=0; i<n-1; i++)
    {
    	int from, to;
    	cin>>from>>to;
    	g[from].pb(to);
    	g[to].pb(from);
    }
    for(int i=1; i<=n; i++)
    {
    	if(g[i].size()==2)
    		goto no;
    }
    yes:
    printnl("YES"); return 0;
    no:
    printnl("NO");
}


#include <bits/stdc++.h>
#define ll long long
#define lld long double
#define mod 1000000007
#define maxx 2305843009213693952
#define print(x) cout<<setprecision(18)<<fixed<<x<<endl;
#define boost ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    boost;
    ll N,ans = 0,maxi = -1e9;
    cin>>N;
    pair<ll,ll>  al_sk[N+1];
    for(ll i=0;i<N;i++)  cin>>al_sk[i+1].first;

    for(ll i=0;i<N;i++)  cin>>al_sk[i+1].second;

    sort(al_sk+1, al_sk+N+1);
    reverse(al_sk+1, al_sk+N+1);
    // for(ll i=1;i<=N;i++)  cout<<al_sk[i].first<<" ";
    for(ll i=1;i<N;i++)
    {
        if(al_sk[i].first == al_sk[i+1].first && al_sk[i].first != maxx)
        {
            ll A = al_sk[i].first; ans += (al_sk[i].second+al_sk[i+1].second);
            for(ll j = i+2;j<=N;j++)
                if((A&al_sk[j].first) == al_sk[j].first)
                    {
                        ans += al_sk[j].second;
                        al_sk[j].first = maxx;
                    }
            // cout<<ans<<endl;
        }
    }
    cout<<ans<<endl;
}


#include <bits/stdc++.h>
#define ll long long
#define lld long double
#define mod 1000000007
#define maxx 9223372036854775807
#define print(x) cout<<setprecision(18)<<fixed<<x<<endl;
#define boost ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    boost;
    ll N,ans = 0,maxi = -1e9;
    cin>>N;
    pair<ll,ll>  al_sk[N+1];
    for(ll i=0;i<N;i++)  cin>>al_sk[i+1].first;

    for(ll i=0;i<N;i++)  cin>>al_sk[i+1].second;

    sort(al_sk+1, al_sk+N+1);
    reverse(al_sk+1, al_sk+N+1);

    for(ll i=1;i<N;i++)
    {
        if(al_sk[i].first == al_sk[i+1].first)
        {
            ll A = al_sk[i].first; ans = al_sk[i].second+al_sk[i+1].second;
            for(ll j = i+2;j<=N;j++)
            {
                if((A&al_sk[j].first) == al_sk[j].first)
                {
                    ans += al_sk[j].second;
                    A = (A&al_sk[j].first);
                }
            }
            maxi = max(ans,maxi);
        }
    }
    if(maxi == -1e9)  cout<<0<<endl;
    else  cout<<maxi<<endl;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author
 */

#include <iostream>
#include <fstream>

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

#define all(c) c.begin(), c.end()
#define soa(c) sort(all(c))
#define sua(c) accumulate(all(c), 0ll)
#define pb push_back
#define forn(i, n)  for(ll i = 0; i < ll(n); ++i)
#define forn1(i, n) for(ll i = 1; i < ll(n); ++i)
#define nfor(i, n)  for(ll i = ll(n) - 1; i >= 0; --i)
#define nfor1(i, n) for(ll i = ll(n) - 2; i >= 0; --i)
#define forlr(i, l, r) for(ll i = l; i < ll(r); ++i)
#define forrl(i, l, r) for(ll i = ll(r) - 1; i >= l; --i)
#define forr(elem, vec) for(auto & elem : vec)
#define print WhiteSpacedCout(out).start(),
#define dbg(...) pr_dbg(out, #__VA_ARGS__, __VA_ARGS__);
#define all(c) c.begin(), c.end()
#define rall(c) c.rbegin(), c.rend()
#define by(x) [](const auto& a, const auto& b) { return a.x < b.x; } // C++14
#define eq(x) [](const auto& a, const auto& b) { return a.x == b.x; } // C++14
#define fi first
#define se second
#define divceil(x, y) (((x) + (y) - 1) / (y))

template<typename T1, typename T2> std::ostream &operator<<(std::ostream &s, const std::pair<T1,T2> &x){ s << "pair(" << x.first << " ," << x.second << ')'; return s; }
template<typename T> std::ostream &operator<<(std::ostream &s, const std::vector<T> &x){ if(x.empty()){ s << "vector(empty)"; return s;} s << "vector("; for(size_t i = 0; i < x.size() - 1; i++){ s << x[i] << ", "; } s << x[x.size() - 1] << ')'; return s; }
template<typename V>             std::ostream &operator<<(std::ostream &s, const std::set<V> &x)        { if(x.empty()){ s << "set(empty)";      return s;} s << "set(";      for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename V>             std::ostream &operator<<(std::ostream &s, const std::multiset<V> &x)   { if(x.empty()){ s << "multiset(empty)"; return s;} s << "multiset("; for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename K, typename V> std::ostream &operator<<(std::ostream &s, const std::map<K, V> &x)     { if(x.empty()){ s << "map(empty)";      return s;} s << "map(";      for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v.fi << "=" << v.se; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename K, typename V> std::ostream &operator<<(std::ostream &s, const std::multimap<K, V> &x){ if(x.empty()){ s << "multimap(empty)"; return s;} s << "multimap("; for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v.fi << "=" << v.se; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename T1, typename T2> std::istream & operator >> (std::istream &s, std::pair<T1,T2> & pair){ s >> pair.fi >> pair.se; return s;  }

struct WhiteSpacedCout { bool space; std::ostream& out; explicit WhiteSpacedCout(std::ostream& out) : space(false), out(out) {} ~WhiteSpacedCout() { out << '\n'; }  WhiteSpacedCout & start() {return *this;} template <typename T> WhiteSpacedCout &operator , (const T &t) { if (space) out << ' '; else space = true; out << t; return *this; } };

template<typename T> static void pr_dbg(std::ostream &s, const string& name, T t) { s << name << ": " << t << endl; }
template<typename T, typename ... Types> static void pr_dbg(std::ostream &s, const string& names, T t, Types ... rest) { auto comma_pos = names.find(','); s << names.substr(0, comma_pos) << ": " << t << ", "; pr_dbg(s, string(names, names.find_first_not_of(" \t\n", comma_pos + 1)), rest ...); }

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<vll> vvll;
typedef vector<pll> vpll;
typedef vector<vll> Graph;

template<typename T> static vector<T> vin(ll n, std::istream& in){ vector<T> ret; forn(i, n){ T val; in >> val; ret.pb(val); } return ret; }
template<typename T> static vector<pair<T, ll>> vini(ll n, std::istream& in){ vector<pair<T, ll>> ret; forn(i, n){ T val; in >> val; ret.pb({val, i}); } return ret; }
template<typename T> static T read(std::istream& in){ T val; in >> val; return val; }
template<typename T> static void answer(const T & cont, std::ostream & out){ for(auto & v : cont){ out << v << ' '; }; out << '\n'; }

#define read_vll(n)   vin<ll>(n, in)
#define read_vlli(n)  vini<ll>(n, in)
#define read_vpll(n)  vin<pll>(n, in)
#define read_vplli(n) vini<pll>(n, in)
#define read_vs(n)    vin<string>(n, in)
#define read_s()      read<string>(in)
#define read_ll()     read<ll>(in)
#define read_pll()    read<pll>(in)

#define max_ll std::numeric_limits<ll>::max()
#define min_ll std::numeric_limits<ll>::min()
#define min3(a,b,c) std::min(std::min(a, b), c)
#define max3(a,b,c) std::max(std::max(a, b), c)

template <typename It, typename T = typename It::value_type, typename Pr = typename std::function<void(It, It)>, typename Eq = typename std::function<bool(T, T)> >
void itersame(It begin, It end, Pr process, Eq equal = std::equal_to<T>())
{
	for (auto b = begin, e = begin; e != end;)
	{
		e = find_if(b, end, [&](T pr) { return !equal(pr, *b); });
		process(b, e);
		b = e;
	}
}

#define itersameall(c, cmd) itersame(all(c), [&](auto b, auto e){ cmd })

class BMarchinISbori
{
public:
	void solve(std::istream& in, std::ostream& out)
	{
		ll n = read_ll();
		auto a = read_vll(n);
		auto b = read_vll(n);

		vb take(n);

		forn(i, n){
			ll same = 0;

			vb t(n);

			forn(j, n){
				if((a[i] | a[j]) == a[i]){
					t[j] = true;
				}

				if(a[i] == a[j])
					same++;
			}

			if(same > 1)
			{
				forn(i, n){
					take[i] = take[i] || t[i];
				}
			}
		}

		ll ans = 0;

		forn(i, n){
			if(take[i])
				ans += b[i];
		}

		print ans;
	}
};

int main() {
	ios_base::sync_with_stdio(0);
	cout << std::setprecision(10);
	BMarchinISbori solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
	return 0;
}


/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author
 */

#include <iostream>
#include <fstream>

#include <iostream>

#include <bits/stdc++.h>

using namespace std;

#define all(c) c.begin(), c.end()
#define soa(c) sort(all(c))
#define sua(c) accumulate(all(c), 0ll)
#define pb push_back
#define forn(i, n)  for(ll i = 0; i < ll(n); ++i)
#define forn1(i, n) for(ll i = 1; i < ll(n); ++i)
#define nfor(i, n)  for(ll i = ll(n) - 1; i >= 0; --i)
#define nfor1(i, n) for(ll i = ll(n) - 2; i >= 0; --i)
#define forlr(i, l, r) for(ll i = l; i < ll(r); ++i)
#define forrl(i, l, r) for(ll i = ll(r) - 1; i >= l; --i)
#define forr(elem, vec) for(auto & elem : vec)
#define print WhiteSpacedCout(out).start(),
#define dbg(...) pr_dbg(out, #__VA_ARGS__, __VA_ARGS__);
#define all(c) c.begin(), c.end()
#define rall(c) c.rbegin(), c.rend()
#define by(x) [](const auto& a, const auto& b) { return a.x < b.x; } // C++14
#define eq(x) [](const auto& a, const auto& b) { return a.x == b.x; } // C++14
#define fi first
#define se second
#define divceil(x, y) (((x) + (y) - 1) / (y))

template<typename T1, typename T2> std::ostream &operator<<(std::ostream &s, const std::pair<T1,T2> &x){ s << "pair(" << x.first << " ," << x.second << ')'; return s; }
template<typename T> std::ostream &operator<<(std::ostream &s, const std::vector<T> &x){ if(x.empty()){ s << "vector(empty)"; return s;} s << "vector("; for(size_t i = 0; i < x.size() - 1; i++){ s << x[i] << ", "; } s << x[x.size() - 1] << ')'; return s; }
template<typename V>             std::ostream &operator<<(std::ostream &s, const std::set<V> &x)        { if(x.empty()){ s << "set(empty)";      return s;} s << "set(";      for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename V>             std::ostream &operator<<(std::ostream &s, const std::multiset<V> &x)   { if(x.empty()){ s << "multiset(empty)"; return s;} s << "multiset("; for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename K, typename V> std::ostream &operator<<(std::ostream &s, const std::map<K, V> &x)     { if(x.empty()){ s << "map(empty)";      return s;} s << "map(";      for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v.fi << "=" << v.se; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename K, typename V> std::ostream &operator<<(std::ostream &s, const std::multimap<K, V> &x){ if(x.empty()){ s << "multimap(empty)"; return s;} s << "multimap("; for(auto it = x.begin(); it != x.end();){ auto & v = *it; s << v.fi << "=" << v.se; if(++it != x.end()) s << ", "; else s << ")"; } return s; }
template<typename T1, typename T2> std::istream & operator >> (std::istream &s, std::pair<T1,T2> & pair){ s >> pair.fi >> pair.se; return s;  }

struct WhiteSpacedCout { bool space; std::ostream& out; explicit WhiteSpacedCout(std::ostream& out) : space(false), out(out) {} ~WhiteSpacedCout() { out << '\n'; }  WhiteSpacedCout & start() {return *this;} template <typename T> WhiteSpacedCout &operator , (const T &t) { if (space) out << ' '; else space = true; out << t; return *this; } };

template<typename T> static void pr_dbg(std::ostream &s, const string& name, T t) { s << name << ": " << t << endl; }
template<typename T, typename ... Types> static void pr_dbg(std::ostream &s, const string& names, T t, Types ... rest) { auto comma_pos = names.find(','); s << names.substr(0, comma_pos) << ": " << t << ", "; pr_dbg(s, string(names, names.find_first_not_of(" \t\n", comma_pos + 1)), rest ...); }

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<vll> vvll;
typedef vector<pll> vpll;
typedef vector<vll> Graph;

template<typename T> static vector<T> vin(ll n, std::istream& in){ vector<T> ret; forn(i, n){ T val; in >> val; ret.pb(val); } return ret; }
template<typename T> static vector<pair<T, ll>> vini(ll n, std::istream& in){ vector<pair<T, ll>> ret; forn(i, n){ T val; in >> val; ret.pb({val, i}); } return ret; }
template<typename T> static T read(std::istream& in){ T val; in >> val; return val; }
template<typename T> static void answer(const T & cont, std::ostream & out){ for(auto & v : cont){ out << v << ' '; }; out << '\n'; }

#define read_vll(n)   vin<ll>(n, in)
#define read_vlli(n)  vini<ll>(n, in)
#define read_vpll(n)  vin<pll>(n, in)
#define read_vplli(n) vini<pll>(n, in)
#define read_vs(n)    vin<string>(n, in)
#define read_s()      read<string>(in)
#define read_ll()     read<ll>(in)
#define read_pll()    read<pll>(in)

#define max_ll std::numeric_limits<ll>::max()
#define min_ll std::numeric_limits<ll>::min()
#define min3(a,b,c) std::min(std::min(a, b), c)
#define max3(a,b,c) std::max(std::max(a, b), c)

class BMarchinISbori
{
public:
	void solve(std::istream& in, std::ostream& out)
	{
		ll n = read_ll();
		auto a = read_vll(n);
		auto b = read_vll(n);

		ll ans = 0;

		forn(i, n){
			ll cand = 0;
			ll same = 0;

			forn(j, n){
				if((a[i] | a[j]) == a[i]){
					cand += b[j];
				}

				if(a[i] == a[j])
					same++;
			}

			if(same > 1)
				ans = max(ans, cand);
		}

		print ans;
	}
};

int main() {
	ios_base::sync_with_stdio(0);
	cout << std::setprecision(10);
	BMarchinISbori solver;
	std::istream& in(std::cin);
	std::ostream& out(std::cout);
	solver.solve(in, out);
	return 0;
}


import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        HashMap<Integer,Integer> map=new HashMap();
        HashMap<Integer,Integer> front=new HashMap();
        HashMap<Integer,Integer> same=new HashMap();
        HashMap<Integer,Integer> back=new HashMap();
        int a[]=new int[n];int b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            int x=sc.nextInt();
            int y=sc.nextInt();
            if(!front.containsKey(x))
                front.put(x,1);
            else
                front.put(x,front.get(x)+1);
             if(!back.containsKey(y))
                back.put(y,1);
            else
                back.put(y,back.get(y)+1);
            a[i]=x;b[i]=y;
            if(x==y)
            {
                if(!same.containsKey(x))
                    same.put(x,1);
                else
                    same.put(x,same.get(x)+1);
            }
        }
        int mid=(n/2);
        if(n%2==1)
            mid++;
        int ans=n+2;
        for(int i=0;i<n;i++)
        {
            int fr=front.get(a[i]);
            if(fr>=mid)
            {
                ans=0;
                continue;
            }
            int bk=0;
            if(back.containsKey(a[i]))
                bk=back.get(a[i]);
            int sm=0;
            if(same.containsKey(a[i]))
                sm=same.get(a[i]);
            int tmp=fr+bk-sm;
            if(tmp>=mid)
            {
                int t1=bk-sm;
                if(ans>t1)
                    ans=t1;
            }
        }
        if(ans>n)
            ans=-1;
        System.out.println(ans);
    }
}


import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        HashMap<Integer,Integer> map=new HashMap();
        HashMap<Integer,Integer> front=new HashMap();
        HashMap<Integer,Integer> same=new HashMap();
        HashMap<Integer,Integer> back=new HashMap();
        int a[]=new int[n];int b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            int x=sc.nextInt();
            int y=sc.nextInt();
            if(!front.containsKey(x))
                front.put(x,1);
            else
                front.put(x,front.get(x)+1);
             if(!back.containsKey(y))
                back.put(y,1);
            else
                back.put(y,back.get(y)+1);
            a[i]=x;b[i]=y;
            if(x==y)
            {
                if(!same.containsKey(x))
                    same.put(x,1);
                else
                    same.put(x,same.get(x)+1);
            }
        }
        int mid=(n/2)+1;
        int ans=n+2;
        for(int i=0;i<n;i++)
        {
            int fr=front.get(a[i]);
            if(fr>=mid)
            {
                ans=0;
                continue;
            }
            int bk=0;
            if(back.containsKey(a[i]))
                bk=back.get(a[i]);
            int sm=0;
            if(same.containsKey(a[i]))
                sm=same.get(a[i]);
            int tmp=fr+bk-sm;
            if(tmp>=mid)
            {
                int t1=bk-sm;
                if(ans>t1)
                    ans=t1;
            }
        }
        System.out.println(ans);
    }
}


import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        HashMap<Integer,Integer> map=new HashMap();
        HashMap<Integer,Integer> front=new HashMap();
        HashMap<Integer,Integer> same=new HashMap();
        HashMap<Integer,Integer> back=new HashMap();
        int a[]=new int[n];int b[]=new int[n];
        for(int i=0;i<n;i++)
        {
            int x=sc.nextInt();
            int y=sc.nextInt();
            if(!front.containsKey(x))
                front.put(x,1);
            else
                front.put(x,front.get(x)+1);

            a[i]=x;b[i]=y;
            if(x==y)
            {

                continue;
            }

            if(!back.containsKey(y))
                back.put(y,1);
            else
                back.put(y,back.get(y)+1);
        }
        int mid=(n/2);
        if(n%2==1)
            mid++;
        int ans=n+2;
        for(int i=0;i<n;i++)
        {
            int fr=front.get(a[i]);
            if(fr>=mid)
            {
                ans=0;
                continue;
            }
            int bk=0;

            if(back.containsKey(a[i]))
                bk=back.get(a[i]);

            int tmp=fr+bk;
            if(tmp>=mid)
            {
                int t1=mid-fr;
                if(ans>t1)
                    ans=t1;
            }
        }
        if(ans>n)
        for(int i=0;i<n;i++)
        {
            if(back.get(b[i])>=mid)
            {
                ans=mid;break;
            }
        }
        if(ans>n)ans=-1;
        System.out.println(ans);
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class LittleElephantAndCards {
	public static void main(String args[]) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
		TreeMap<Integer,Integer> front = new TreeMap<Integer, Integer>();
		TreeMap<Integer,Integer> back = new TreeMap<Integer, Integer>();
		int Limit  = n/2 + n%2;
		for (int i=0;i<n;i++)
		{
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (front.containsKey(a))
				front.put(a, front.get(a)+1);
			else
				front.put(a, 1);
			if (a!=b)
			{
				if (back.containsKey(b))
					back.put(b, back.get(b)+1);
				else
					back.put(b, 1);
			}
			Integer c = front.get(a);
			if (c==null)
				c = 0;
			Integer d = back.get(a);
			if (d==null)
				d = 0;
			if (c+d==Limit)
				pq.add(d);
			c = front.get(b);
			if (c==null)
				c = 0;
			d = back.get(b);
			if (d==null)
				d = 0;
			if (c+d==Limit)
				pq.add(d);
		}
		if (pq.size()==0)
			System.out.println(-1);
		else
			System.out.println(pq.peek());
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public boolean ready() throws IOException {return br.ready();}

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class LittleElephantAndCards {
	public static void main(String args[]) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
		TreeMap<Integer,Integer> front = new TreeMap<Integer, Integer>();
		TreeMap<Integer,Integer> back = new TreeMap<Integer, Integer>();
		int Limit  = n/2 + n%2;
		for (int i=0;i<n;i++)
		{
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (front.containsKey(a))
				front.put(a, front.get(a)+1);
			else
				front.put(a, 1);
			if (a!=b)
			{
				if (back.containsKey(b))
					back.put(b, back.get(b)+1);
				else
					back.put(b, 1);
			}
			Integer c = front.get(a);
			if (c==null)
				c = 0;
			Integer d = back.get(a);
			if (d==null)
				d = 0;
			if (c+d>=Limit)
				pq.add(Math.max(Limit-c,0));
			c = front.get(b);
			if (c==null)
				c = 0;
			d = back.get(b);
			if (d==null)
				d = 0;
			if (c+d>=Limit)
				pq.add(Math.max(0,Limit-c));
		}
		if (pq.size()==0)
			System.out.println(-1);
		else
			System.out.println(pq.peek());
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public boolean ready() throws IOException {return br.ready();}

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class LittleElephantAndCards {
	public static void main(String args[]) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
		TreeMap<Integer,Integer> front = new TreeMap<Integer, Integer>();
		TreeMap<Integer,Integer> back = new TreeMap<Integer, Integer>();
		int Limit  = n/2 + n%2;
		for (int i=0;i<n;i++)
		{
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (front.containsKey(a))
				front.put(a, front.get(a)+1);
			else
				front.put(a, 1);

			if (back.containsKey(b))
				back.put(b, back.get(b)+1);
			else
				back.put(b, 1);

			if (front.get(a)+back.get(a)==Limit)
				pq.add(back.get(a));
			if (front.get(b)+back.get(b)==Limit)
				pq.add(back.get(b));
		}
		if (pq.size()==0)
			System.out.println(-1);
		else
			System.out.println(pq.peek());
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public boolean ready() throws IOException {return br.ready();}

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class LittleElephantAndCards {
	public static void main(String args[]) throws IOException
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
		TreeMap<Integer,Integer> front = new TreeMap<Integer, Integer>();
		TreeMap<Integer,Integer> back = new TreeMap<Integer, Integer>();
		int Limit  = n/2 + n%2;
		for (int i=0;i<n;i++)
		{
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (front.containsKey(a))
				front.put(a, front.get(a)+1);
			else
				front.put(a, 1);

			if (back.containsKey(b))
				back.put(b, back.get(b)+1);
			else
				back.put(b, 1);
			Integer c = front.get(a);
			if (c==null)
				c = 0;
			Integer d = back.get(a);
			if (d==null)
				d = 0;
			if (c+d==Limit)
				pq.add(d);
			c = front.get(b);
			if (c==null)
				c = 0;
			d = back.get(b);
			if (d==null)
				d = 0;
			if (c+d==Limit)
				pq.add(d);
		}
		if (pq.size()==0)
			System.out.println(-1);
		else
			System.out.println(pq.peek());
	}
	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public boolean ready() throws IOException {return br.ready();}

	}
}