1. #include "bits/stdc++.h"
  2. // #pragma GCC optimize("O3,unroll-loops")
  3. // #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
  4. using namespace std;
  5. using ll = long long int;
  6. mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
  7.  
  8. int main()
  9. {
  10. ios::sync_with_stdio(false); cin.tie(0);
  11.  
  12. int t; cin >> t;
  13. while (t--) {
  14. int n; cin >> n;
  15. vector<int> a(n), b(n);
  16. array<int, 20> allct{}, hsbct{};
  17. array<array<int, 20>, 20> bitct{};
  18. ll sumB = 0;
  19. for (int &x : a) cin >> x;
  20. for (int &x : b) {
  21. cin >> x;
  22. sumB += x;
  23. if (x == 0) continue;
  24. int hsb = 20;
  25. while (~x&(1<<hsb)) --hsb;
  26. ++hsbct[hsb];
  27. for (int i = 0; i < 20; ++i) {
  28. allct[i] += (x>>i)&1;
  29. bitct[hsb][i] += (x>>i)&1;
  30. }
  31. }
  32. sort(rbegin(a), rend(a));
  33. ll ans = 0;
  34. int hsb = 20;
  35. for (int x : a) {
  36. if (x == 0) {
  37. ans += sumB;
  38. continue;
  39. }
  40. while (~x&(1<<hsb)) --hsb;
  41. // Same hsb -> AND
  42. for (int bit = 0; bit < 20; ++bit) {
  43. if (~x & (1<<bit)) continue;
  44. ans += (1LL<<bit) * bitct[hsb][bit];
  45. }
  46.  
  47. // Different hsb -> XOR
  48. for (int bit = 0; bit < 20; ++bit) {
  49. int ct = 0;
  50. if (x & (1<<bit)) ct = n - allct[bit] - (hsbct[hsb] - bitct[hsb][bit]);
  51. else ct = allct[bit] - bitct[hsb][bit];
  52. ans += (1LL<<bit) * ct;
  53. }
  54. }
  55. cout << ans << '\n';
  56. }
  57. }