Problem:
今年も，全国プログラミング選手権大会の時期がやってきた．全国大会の参加権を賭けた地区大会は，
2
n
チームが1 対1 の勝ち残り式トーナメント方式で対決する．
トーナメント表にはチーム番号
0, . . . 2
n
− 1
が割り振られており，1 回戦から
n
回戦までの対決手順は次の通りである．
1 回戦では，（チーム番号が
l
のチーム）と（チーム番号が
l
+ 1 のチーム）が対決する．(
l
≡ 0 (mod 2))
i + 1
回戦(
1 ≤ i < n
) では，「チーム番号が
l
以上
l + 2
i
未満のチームのうち，
i
回戦までの対決で 1 回も負けていないチーム」と「チーム番号が
l + 2
i
以上
l + 2
i+1
未満のチームのうち，
i
回戦までの対決で一回も負けていないチーム」が対決する．(
l
≡ 0 (mod 2
i
+1
))
n
回戦まで終わると，各チームの順位は 2
n
− (そのチームが勝った回数)
位で確定する．なお，この対決には引き分けが存在しないため，対決したチームのいずれか一方が勝ち，もう一方が負ける．
晴れて地区大会の代表に選ばれた私達は，他の地区大会の結果をマネージャーに調べてもらうことにした．ここで調べてもらった結果が「マネージャーから受け取った順位表」であった．「マネージャーから受け取った順位表」をより詳細に説明すると，長さ 2
n
の数列で
i ( 0 ≤ i ≤ 2
n
− 1 )
番目の要素にチーム番号
i
のチームの順位が書かれているものである．
だが，「マネージャーから受け取った順位表」には同じ順位が大量に並んでいた！トーナメントのルール上，同じ順位が大量に並ぶなんてありえないはずだ．そこで，「マネージャーから受け取った順位表」を「無矛盾な順位表」にするために順位を変更するチーム数の最小値を計算してどのくらい順位表が間違っているかをマネージャーに教えてあげよう．「無矛盾な順位表」とは，順位が確定したトーナメントの結果として起こりうる順位表のことを表す．
Input
入力には，「マネージャーから受け取った順位表」が以下の形式で与えられる．
n
m
a
0
a
1
. . .
a
m
b
0
b
1
. . .
b
m−1
1 行目は
n, m
の2 個の整数からなり， 2
n
は「地区大会の参加チーム数」，
m
は「『マネージャーから受け取った順位表』で連続した順位が並んでいる区間の個数」を表す．
2 行目は
a
i
(0 ≤ i ≤ m)
の
m + 1
個の整数からなり，各
a
i
は「『マネージャーから受け取った順位表』で連続した順位が並んでいる区間の区切り位置」を表す．
3 行目は
b
i
(0 ≤ i < m)
の
m
個の整数からなり，各2
b
i
は「『マネージャーから受け取った順位表』におけるチーム番号が
a
i
以上
a
i+1
未満のチームの順位」を表す．
Constraints
1 ≤
n
≤ 30
1 ≤
m
≤ 10,000
0 = a
0
< a
1
≤ . . . ≤ a
m−1
< a
m
= 2
n
0 ≤
b
i
≤
n
Output
「マネージャーから受け取った順位表」を「無矛盾な順位表」にするために順位を変更するチーム数の最小値を1 行に出力せよ．
Sample Input 1
1 1
0 2
1
Output for the Sample Input 1
1
参加チーム数が2 の「無矛盾な順位表」は，{"チーム番号 0 のチームの順位", "チーム番号 1 のチームの順位"} として {1, 2} と {2, 1} の2 通りがある．順位表 {2, 2} を「無矛盾な順位表」に修正するためには，いずれかのチームの順位を 1 に変更しなければならない．
Sample Input 2
2 3
0 1 2 4
0 1 2
Output for the Sample Input 2
2
Sample Input 3
2 3
0 1 3 4
0 2 1
Output for the Sample Input 3
0
Sample Input 4
4 5
0 1 2 4 8 16
0 1 2 3 4
Output for the Sample Input 4
10

Submitted solutions:

code_snippet: // AOJ #2646 Tournament
// 2025.3.20

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

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int Cin() {  // 整数の入力
	int n = 0; int c = gc();
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void Cout(int n) { // 整数の表示（出力）
	char b[30];
	if (!n) pc('0');
	else {
		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

int main(){
    int n = Cin(), m = Cin();
    vector<int> A(m+1), B(m);
    for(int i = 0; i <= m; i++) A[i] = Cin();
    for(int i = 0; i < m; i++)  B[i] = Cin();

    auto dfs = [&](auto &dfs, int L, int R, int C, int idx) -> vector<int> {
        vector<int> res(C+1, R - L);
        if(A[idx] <= L && R <= A[idx+1]){
            int v = B[idx];
            if(v <= C) res[C - v] = R - L - 1;
            else for(int j = 0; j <= C; j++) res[j] = (R - L) - (1 << (v - C - 1));
        }
        else{
            int mid = L + (R - L) / 2;
            int nIdx = -1;
            auto Lres = dfs(dfs, L, mid, C + 1, idx);
            for(int i = idx; i < m; i++){
                if(A[i] <= mid && mid < A[i+1]){
                    nIdx = i;
                    break;
                }
            }
            auto Rres = dfs(dfs, mid, R, C + 1, nIdx);
            for(int j = 0; j <= C; j++){
                res[j] = min(res[j], Lres[0] + Rres[j+1]);
                res[j] = min(res[j], Lres[j+1] + Rres[0]);
            }
        }
        return res;
    };

    Cout(dfs(dfs, 0, (1 << n), 0, 0)[0]);
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3520
final_rank: 1

code_snippet: // AOJ #2646 Tournament
// 2025.3.20

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

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;
    vector<int> A(m+1), B(m);
    for(int i = 0; i <= m; i++) cin >> A[i];
    for(int i = 0; i < m; i++)  cin >> B[i];

    auto dfs = [&](auto &dfs, int L, int R, int C, int idx) -> vector<int> {
        vector<int> res(C+1, R - L);
        if(A[idx] <= L && R <= A[idx+1]){
            int v = B[idx];
            if(v <= C) res[C - v] = R - L - 1;
            else for(int j = 0; j <= C; j++) res[j] = (R - L) - (1 << (v - C - 1));
        }
        else{
            int mid = L + (R - L) / 2;
            int nIdx = -1;
            auto Lres = dfs(dfs, L, mid, C + 1, idx);
            for(int i = idx; i < m; i++){
                if(A[i] <= mid && mid < A[i+1]){
                    nIdx = i;
                    break;
                }
            }
            auto Rres = dfs(dfs, mid, R, C + 1, nIdx);
            for(int j = 0; j <= C; j++){
                res[j] = min(res[j], Lres[0] + Rres[j+1]);
                res[j] = min(res[j], Lres[j+1] + Rres[0]);
            }
        }
        return res;
    };

    cout << dfs(dfs, 0, (1 << n), 0, 0)[0] << endl;
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3552
final_rank: 3

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    int N, M;
    cin >> N >> M;
    vector<int> A(M+1), B(M);
    rep(i,0,M+1) cin >> A[i];
    rep(i,0,M) cin >> B[i];
    vector<map<int,int>> memo(N+1);
    auto DFS = [&](auto self, int L, int Dep, int X) -> int {
        if (Dep == X && memo[Dep].count(L)) return memo[Dep][L];
        int LID = UB(A,L)-1;
        int R = L + (1<<(N-Dep));
        if (Dep == N) {
            if (B[LID] == X) return 0;
            else return 1;
        }
        if (R <= A[LID+1]) { //{X,Dep+1,Dep+2,Dep+2,Dep+3,...}
            int COUNT = 0;
            if (B[LID] > Dep) COUNT = 1<<(B[LID]-Dep-1);
            else if (B[LID] == X) COUNT = 1;
            else COUNT = 0;
            return (1<<(N-Dep)) - COUNT;
        }
        int MID = L + (1<<(N-Dep-1));
        int Ret = min(self(self,L,Dep+1,X)+self(self,MID,Dep+1,Dep+1), self(self,L,Dep+1,Dep+1)+self(self,MID,Dep+1,X));
        if (Dep == X) memo[Dep][L] = Ret;
        return Ret;
    };
    cout << DFS(DFS,0,0,0) << endl;
}
accuracy: 1
time_ms: 630
memory_kb: 10684
final_rank: 10

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

int main() {
	int N, M;
	cin >> N >> M;
	vector<long long> A(M + 1);
	vector<int> B(M);
	for (int i = 0; i <= M; i++) {
		cin >> A[i];
	}
	for (int i = 0; i < M; i++) {
		cin >> B[i];
	}
	const long long INF = (3LL << 59);
	auto calc = [&](auto& self, long long l, long long r, int level) -> vector<long long> {
		int pos = lower_bound(A.begin(), A.end(), l + 1) - A.begin();
		if (A[pos] >= r) {
			int rank = B[pos - 1];
			vector<long long> subres(level + 1);
			if (rank > level) {
				for (int i = 0; i <= level; i++) {
					subres[i] = ((r - l) >> (N - rank + 1));
				}
			}
			else {
				for (int i = 0; i <= level; i++) {
					subres[i] = (i == rank ? 1 : 0);
				}
			}
			return subres;
		}
		vector<long long> resl = self(self, l, (l + r) / 2, level + 1);
		vector<long long> resr = self(self, (l + r) / 2, r, level + 1);
		vector<long long> res(level + 1);
		for (int i = 0; i <= level; i++) {
			res[i] = max(resl[i] + resr[level + 1], resl[level + 1] + resr[i]);
		}
		return res;
	};
	vector<long long> ans = calc(calc, 0, (1LL << N), 0);
	cout << (1LL << N) - ans[0] << endl;
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3460
final_rank: 5

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n,m; cin >> n >> m;
    vector<int> a(m+1);
    for(int i=0;i<=m;i++){
        cin >> a[i];
    }
    vector<int> b(m);
    for(int i=0;i<m;i++){
        cin >> b[i];
    }
    
    // 区間[l,r)について優勝者があと(0,1,,,c)回勝利する場合の最小コスト
    auto dfs = [&](auto dfs,int l,int r,int c,int lid)->vector<int>{
        vector<int> res(c+1, r-l);
        // 区間が完全に定数で包含されてる場合
        if(a[lid] <= l and r <= a[lid+1]){
            int val = b[lid];
            if(val <= c){
                res[c-val] = r-l-1;
            }
            else{
                for(int j=0;j<=c;j++){
                    res[j] = (r-l) - (1<<(val-c-1));
                }
            }
        }
        else{
            int nr = l+(r-l)/2;
            int nlid = -1;
            auto rl = dfs(dfs,l,nr,c+1,lid);
            for(int i=lid;i<m;i++){
                if(a[i] <= nr and nr < a[i+1]){
                    nlid = i; break;
                }
            }
            auto rr = dfs(dfs,nr,r,c+1,nlid);
            for(int i=0;i<=c;i++){
                res[i] = min(res[i], rl[0]+rr[i+1]);
                res[i] = min(res[i], rl[i+1]+rr[0]);
            }
        }

        return res;
    };
    cout << dfs(dfs,0,(1<<n),0,0)[0] << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 3520
final_rank: 1

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n,m; cin >> n >> m;
    vector<int> a(m+1);
    for(int i=0;i<=m;i++){
        cin >> a[i];
    }
    vector<int> b(m);
    for(int i=0;i<m;i++){
        cin >> b[i];
    }
    {
        vector<int> na = {a[0], a[1]};
        vector<int> nb = {b[0]};
        for(int i=1;i<m;i++){
            if(b[i] == nb.back()){
                na.pop_back();
                na.push_back(a[i+1]);
            }
            else{
                na.push_back(a[i+1]);
                nb.push_back(b[i]);
            }
        }
        swap(a,na);
        swap(b,nb);
        m = b.size();
    }
    // 区間[l,r)について優勝者があと(0,1,,,c)回勝利する場合の最小コスト
    auto dfs = [&](auto dfs,int l,int r,int c,int lid)->vector<int>{
        vector<int> res(c+1, r-l);
        // 区間が完全に定数で包含されてる場合
        if(a[lid] <= l and r <= a[lid+1]){
            int val = b[lid];
            if(val <= c){
                res[c-val] = r-l-1;
            }
            else{
                for(int j=0;j<=c;j++){
                    res[j] = (r-l) - (1<<(val-c-1));
                }
            }
        }
        else{
            int nr = l+(r-l)/2;
            int nlid = -1;
            auto rl = dfs(dfs,l,nr,c+1,lid);
            for(int i=lid;i<m;i++){
                if(a[i] <= nr and nr < a[i+1]){
                    nlid = i; break;
                }
            }
            auto rr = dfs(dfs,nr,r,c+1,nlid);
            for(int i=0;i<=c;i++){
                res[i] = min(res[i], rl[0]+rr[i+1]);
                res[i] = min(res[i], rl[i+1]+rr[0]);
            }
        }

        return res;
    };
    cout << dfs(dfs,0,(1<<n),0,0)[0] << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 3640
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

template <class T>
bool chmin(T &a, const T &b) {
  if (a <= b) return false;
  a = b;
  return true;
}

template <class T>
bool chmax(T &a, const T &b) {
  if (a >= b) return false;
  a = b;
  return true;
}

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> a(m + 1), b(m);
  cin >> a >> b;

  function<vector<int>(int, int, int)> rec = [&](int l, int r, int d) {
    // constant range check
    int k = upper_bound(all(a), l) - a.begin() - 1;
    assert(k >= 0);

    if (a[k] <= l && r <= a[k + 1]) {
      vector<int> res(n + 1, 0);
      for (int i = 0; i <= n; i++) {
        if (b[k] == i) {
          res[i] = r - l - 1;
        } else if (b[k] >= d + 1) {
          res[i] = r - l - (1 << (b[k] - d - 1));
        } else {
          res[i] = r - l;
        }
      }
      return res;
    }

    assert(d < n);
    int mid = (l + r) >> 1;
    auto L = rec(l, mid, d + 1), R = rec(mid, r, d + 1);
    vector<int> res(n + 1, INF);
    for (int i = 0; i <= n; i++) {
      chmin(res[i], L[i] + R[d + 1]);
      chmin(res[i], L[d + 1] + R[i]);
    }
    return res;
  };

  cout << rec(0, (1 << n), 0)[0] << endl;
  return;
}

int main() {
  fastio();
  if (!multitest) {
    solve();
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3540
final_rank: 6

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

template <class T>
bool chmin(T &a, const T &b) {
  if (a <= b) return false;
  a = b;
  return true;
}

template <class T>
bool chmax(T &a, const T &b) {
  if (a >= b) return false;
  a = b;
  return true;
}

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> a(m + 1), b(m);
  cin >> a >> b;

  auto encode = [](int l, int d, int winner) {
    return (static_cast<ll>(l) << 10) + (static_cast<ll>(d) << 5) + winner;
  };

  auto dp = vect(n + 1, vect(n + 1, map<int, int>()));

  function<int(int, int, int, int)> rec = [&](int l, int r, int winner, int d) {
    assert(r - l == (1 << (n - d)));
    auto it = dp[d][winner].find(l);
    if (it != dp[d][winner].end()) return it->second;

    // constant range check
    int k = upper_bound(all(a), l) - a.begin() - 1;
    assert(k >= 0);
    int res = INF;

    if (a[k] <= l && r <= a[k + 1]) {
      if (b[k] == winner) {
        res = r - l - 1;
      } else if (b[k] >= d + 1) {
        res = r - l - (1 << (b[k] - d - 1));
      } else {
        res = r - l;
      }
      if (winner != d) return res;
      return dp[d][winner][l] = res;
    }

    int mid = (l + r) >> 1;
    chmin(res, rec(l, mid, winner, d + 1) + rec(mid, r, d + 1, d + 1));
    chmin(res, rec(l, mid, d + 1, d + 1) + rec(mid, r, winner, d + 1));

    if (winner != d) return res;
    return dp[d][winner][l] = res;
  };

  cout << rec(0, (1 << n), 0, 0) << endl;
  return;
}

int main() {
  fastio();
  if (!multitest) {
    solve();
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 530
memory_kb: 18152
final_rank: 9

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

template <class T>
bool chmin(T &a, const T &b) {
  if (a <= b) return false;
  a = b;
  return true;
}

template <class T>
bool chmax(T &a, const T &b) {
  if (a >= b) return false;
  a = b;
  return true;
}

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

void solve() {
  int n, m;
  cin >> n >> m;
  vector<int> a(m + 1), b(m);
  cin >> a >> b;

  auto encode = [](int l, int d, int winner) {
    return (static_cast<ll>(l) << 10) + (static_cast<ll>(d) << 5) + winner;
  };

  auto dp = vect(n + 1, vect(n + 1, unordered_map<int, int>()));

  function<int(int, int, int, int)> rec = [&](int l, int r, int winner, int d) {
    assert(r - l == (1 << (n - d)));
    auto it = dp[d][winner].find(l);
    if (it != dp[d][winner].end()) return it->second;

    // constant range check
    int k = upper_bound(all(a), l) - a.begin() - 1;
    assert(k >= 0);
    int res = INF;

    if (a[k] <= l && r <= a[k + 1]) {
      if (b[k] == winner) {
        res = r - l - 1;
      } else if (b[k] >= d + 1) {
        res = r - l - (1 << (b[k] - d - 1));
      } else {
        res = r - l;
      }
      if (winner != d) return res;
      return dp[d][winner][l] = res;
    }

    int mid = (l + r) >> 1;
    chmin(res, rec(l, mid, winner, d + 1) + rec(mid, r, d + 1, d + 1));
    chmin(res, rec(l, mid, d + 1, d + 1) + rec(mid, r, winner, d + 1));

    if (winner != d) return res;
    return dp[d][winner][l] = res;
  };

  cout << rec(0, (1 << n), 0, 0) << endl;
  return;
}

int main() {
  fastio();
  if (!multitest) {
    solve();
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 290
memory_kb: 16380
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=200005,INF=1<<30;

vector<int> A,B;
int cn=0;
map<pair<int,short>,int> MA,cnt;
int solve(int l,int r,short x,short rui){
    if(MA.count(mp(l,x))) return MA[mp(l,x)];
    cn++;
    auto a=upper_bound(all(A),l);
    if(r<=(*a)){
        a--;
        int p=a-A.begin();
        if(x==rui){
            if(B[p]>rui) return 0;
            if(rui>=3) return MA[mp(l,x)]=1<<(max(0,x-1-B[p]));
            return 1<<(max(0,x-1-B[p]));
        }else{
            if(B[p]==x) return 1;
            if(B[p]>=rui) return 0;
            if(rui>=3) return MA[mp(l,x)]=1<<(max(0,rui-1-B[p]));
            return 1<<(max(0,rui-1-B[p]));
        }
    }else{
        int res=0;
        int k=rui-1;
        chmax(res,solve(l,(l+r)/2,x,k)+solve((l+r)/2,r,k,k));
        chmax(res,solve(l,(l+r)/2,k,k)+solve((l+r)/2,r,x,k));
        if(rui>=3) return MA[mp(l,x)]=res;
        return res;
    }
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    int N,M;cin>>N>>M;
    A.resize(M+1);B.resize(M);
    for(int i=0;i<=M;i++) cin>>A[i];
    for(int i=0;i<M;i++){
        cin>>B[i];
        B[i]=N-B[i];
    }
    
    int a=solve(0,(1<<N)/2,N,N-1)+solve((1<<N)/2,(1<<N),N-1,N-1);
    int b=solve(0,(1<<N)/2,N-1,N-1)+solve((1<<N)/2,(1<<N),N,N-1);
    cout<<(1<<N)-max(a,b)<<endl;
}
accuracy: 1
time_ms: 1500
memory_kb: 126220
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=200005,INF=1<<30;

vector<int> A,B;
int cn=0;
map<pair<int,short>,short> MA;
short solve(int l,int r,short x,short rui){
    //cout<<l<<" "<<r<<" "<<x<<" "<<rui<<endl;
    if(MA.count(mp(l,x))) return MA[mp(l,x)];
    cn++;
    auto a=upper_bound(all(A),l);
    if(r<=(*a)){
        a--;
        int p=a-A.begin();
        if(x==rui){
            if(B[p]>rui) return 0;
            return MA[mp(l,x)]=1<<(max(0,x-1-B[p]));
        }else{
            if(B[p]==x) return 1;
            if(B[p]>=rui) return 0;
            return MA[mp(l,x)]=1<<(max(0,rui-1-B[p]));
        }
    }else{
        int res=0;
        int k=rui-1;
        chmax(res,solve(l,(l+r)/2,x,k)+solve((l+r)/2,r,k,k));
        chmax(res,solve(l,(l+r)/2,k,k)+solve((l+r)/2,r,x,k));
        return MA[mp(l,x)]=res;
    }
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    int N,M;cin>>N>>M;
    A.resize(M+1);B.resize(M);
    for(int i=0;i<=M;i++) cin>>A[i];
    for(int i=0;i<M;i++){
        cin>>B[i];
        B[i]=N-B[i];
    }
    
    int a=solve(0,(1<<N)/2,N,N-1)+solve((1<<N)/2,(1<<N),N-1,N-1);
    int b=solve(0,(1<<N)/2,N-1,N-1)+solve((1<<N)/2,(1<<N),N,N-1);
    cout<<(1<<N)-max(a,b)<<endl;
}
accuracy: 0.35
time_ms: 1230
memory_kb: 114364
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
void dfs1(vector<int> &id, vector<int> &a, int l, int r, int i){
  int L = upper_bound(a.begin(), a.end(), l) - a.begin() - 1;
  int R = lower_bound(a.begin(), a.end(), r) - a.begin() - 1;
  if (L != R){
    id.push_back(i);
    int m = (l + r) / 2;
    dfs1(id, a, l, m, i * 2 + 1);
    dfs1(id, a, m, r, i * 2 + 2);
  }
}
int dfs2(vector<vector<int>> &dp, vector<int> &id, vector<int> &a, vector<int> &b, int l, int r, int i, int t, int x){
  int L = upper_bound(a.begin(), a.end(), l) - a.begin() - 1;
  int R = lower_bound(a.begin(), a.end(), r) - a.begin() - 1;
  if (L == R){
    int ans = r - l;
    if (b[L] == t){
      ans--;
    }
    if (b[L] > x){
      ans -= 1 << (b[L] - x - 1);
    }
    return ans;
  } else {
    int p = lower_bound(id.begin(), id.end(), i) - id.begin();
    if (dp[t][p] == -1){
      int m = (l + r) / 2;
      int l1 = dfs2(dp, id, a, b, l, m, i * 2 + 1, t, x + 1);
      int l2 = dfs2(dp, id, a, b, l, m, i * 2 + 1, x + 1, x + 1);
      int r1 = dfs2(dp, id, a, b, m, r, i * 2 + 2, t, x + 1);
      int r2 = dfs2(dp, id, a, b, m, r, i * 2 + 2, x + 1, x + 1);
      dp[t][p] = min(l1 + r2, l2 + r1);
    }
    return dp[t][p];
  }
}
int main(){
  int n, m;
  cin >> n >> m;
  vector<int> a(m + 1);
  for (int i = 0; i <= m; i++){
    cin >> a[i];
  }
  vector<int> b(m);
  for (int i = 0; i < m; i++){
    cin >> b[i];
  }
  vector<int> id;
  dfs1(id, a, 0, 1 << n, 0);
  sort(id.begin(), id.end());
  int cnt = id.size();
  vector<vector<int>> dp(n, vector<int>(cnt, -1));
  cout << dfs2(dp, id, a, b, 0, 1 << n, 0, 0, 0) << endl; 
}
accuracy: 1
time_ms: 700
memory_kb: 22572
final_rank: 14

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
using namespace std;

//#define int long long
typedef long long ll;

typedef unsigned long long ul;
typedef unsigned int ui;
constexpr ll mod = 998244353;
const ll INF = mod * mod;
typedef pair<int, int>P;
#define stop char nyaa;cin>>nyaa;
#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-12;
const ld pi = acosl(-1.0);

ll mod_pow(ll x, ll n, ll m = mod) {
	if (n < 0) {
		ll res = mod_pow(x, -n, m);
		return mod_pow(res, m - 2, m);
	}
	if (abs(x) >= m)x %= m;
	if (x < 0)x += m;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	ll n;
	modint() :n(0) { ; }
	modint(ll m) :n(m) {
		if (n >= mod)n %= mod;
		else if (n < 0)n = (n % mod + mod) % mod;
	}
	operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
	if (n == 0)return modint(1);
	modint res = (a * a) ^ (n / 2);
	if (n % 2)res = res * a;
	return res;
}

ll inv(ll a, ll p) {
	return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) { a = a / b; return a; }
const int max_n = 1 << 22;
modint fact[max_n], factinv[max_n];
void init_f() {
	fact[0] = modint(1);
	for (int i = 0; i < max_n - 1; i++) {
		fact[i + 1] = fact[i] * modint(i + 1);
	}
	factinv[max_n - 1] = modint(1) / fact[max_n - 1];
	for (int i = max_n - 2; i >= 0; i--) {
		factinv[i] = factinv[i + 1] * modint(i + 1);
	}
}
modint comb(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[a - b];
}

ll dot(LP a, LP b) {
	return a.first * b.first + a.second * b.second;
}
ll cross(LP a, LP b) {
	return a.first * b.second - a.second * b.first;
}
ll norm2(LP a) {
	return a.first * a.first + a.second * a.second;
}
int ccw(LP a, LP b, LP c) {
	b.first -= a.first; b.second -= a.second;
	c.first -= a.first; c.second -= a.second;
	if (cross(b, c) > 0)return 1;//counter clockwise
	if (cross(b, c) < 0)return -1;//clockwise
	if (dot(b, c) < 0)return 2;//c--a--b on line
	if (norm2(b) < norm2(c))return -2;//a--b--c on line
	return 0;//a--c--b on line
}

ll calc_area(LP a, LP b, LP c) {
	ll x1 = b.first - a.first;
	ll x2 = c.first - a.first;
	ll y1 = b.second - a.second;
	ll y2 = c.second - a.second;
	return abs(x1 * y2 - x2 * y1);
}
vector<ll> calc_val(vector<LP>v) {
	vector<ll> res;
	res.push_back(0);
	ll score = 0;
	vector<LP> dow, up;
	auto add = [&](LP p) {
		if (dow.empty()) {
			dow.push_back(p);
			up.push_back(p);
		}
		else {
			score += calc_area(dow.back(), up.back(), p);
			while (dow.size() >= 2 && ccw(dow[dow.size() - 2], dow[dow.size() - 1], p) != 1) {
				score += calc_area(dow[dow.size() - 2], dow[dow.size() - 1], p);
				dow.pop_back();
			}
			while (up.size() >= 2 && ccw(up[up.size() - 2], up[up.size() - 1], p) != -1) {
				score += calc_area(up[up.size() - 2], up[up.size() - 1], p);
				up.pop_back();
			}
			dow.push_back(p);
			up.push_back(p);
		}
	};
	rep(i, v.size()) {
		int le = i;
		while (i + 1 < v.size() && v[i].first == v[i + 1].first)i++;
		for (int j = le; j <= i; j++) {
			add(v[j]);
		}
		res.push_back(score);
	}
	return res;
}
void solve() {
	int n, m; cin >> n >> m;


	int pre = 0;
	vector<int> a(m + 1); rep(i, m + 1)cin >> a[i];
	vector<int> b(m); rep(i, m)cin >> b[i];

	vector<vector<P>> v(n + 2);
	rep(i, m) {
		int le = a[i], ri = a[i + 1];
		if (le < ri) {
			vector<P> vs;
			vs.push_back({ le,ri });
			for (int j = n; j >= 0; j--) {
				vector<P> cop;
				int k = (1 << j);
				for (P p : vs) {
					int l = p.first, r = p.second;
					int d = k * ((l + k - 1) / k);
					//cout << i << " " <<j<<" "<< l << " " << d << " " << r << "\n";
					if (l < d) {
						cop.push_back({ l,min(d,r) });
					}
					if (d < r) {
						if (r >= d + k) {
							v[j].push_back({ d / k,b[i] });
							if (d + k < r) {
								cop.push_back({ d + k,r });
							}
						}
						else {
							cop.push_back({ d,r });
						}
					}
				}
				swap(cop, vs);
			}
		}
		//cout << v[0].size() << "\n";
	}
	int ans = 0;
	vector<vector<vector<int>>> vals(n + 1);
	//cout << v[1].size() << "\n";
	for (int j = 0; j <= n; j++) {
		int key = n + 1 - j;
		//cout << "!!! " << v[j].size() << "\n";
		sort(all(v[j]));
		
		for (P p : v[j]) {
			//cout << "??? " << j << " " << p.first << "\n";
			if (p.first % 2 == 0) {
				v[j + 1].push_back({ p.first / 2,-1 });
			}
			if (p.second < 0) {
				int loc = lower_bound(all(v[j - 1]), P{ 2 * p.first,-1 }) - v[j - 1].begin();
				vector<int> vl = vals[j - 1][loc];
				vector<int> vr = vals[j - 1][loc + 1];
				bool exil = false, exir = false;
				for (int col : vl)if (col == key||col<0)exil = true;
				for (int col : vr)if (col == key||col<0)exir = true;
				if (exil && exir) {
					for (int col : vr)vl.push_back(col);
					sort(all(vl));
					vl.erase(unique(all(vl)), vl.end());
					vals[j].push_back(vl); continue;
				}
				else if (exil) {
					vals[j].push_back(vr); continue;
				}
				else if (exir) {
					vals[j].push_back(vl); continue;
				}
				for (int col : vr)vl.push_back(col);
				sort(all(vl));
				vl.erase(unique(all(vl)), vl.end());
				ans++;
				vals[j].push_back(vl);
			}
			else {
				if (key > p.second) {
					ans += (1 << j) - 1;
					vals[j].push_back({ p.second });
				}
				else {
					ans += (1 << j);
					ans -= (1 << (p.second - key));
					vals[j].push_back({ -1 });
				}
			}
		}
	}
	bool exi = false;
	for (int col : vals[n][0]) {
		if (col < 0 || col == 0)exi = true;
	}
	if (!exi)ans++;
	cout << ans << "\n";
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	//cout << fixed << setprecision(10);
	//init_f();
	//init();
	//expr();
	//int t; cin >> t; rep(i, t)
	solve();
	return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 88168
final_rank: 15

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2646"

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

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
#endif
//BEGIN CUT HERE
struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#endif
//BEGIN CUT HERE
template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  int h,w;
  cin>>h>>w;
  vector<string> st(h);
  for(int i=0;i<h;i++) cin>>st[i];

  vector<vector<int> > used(h,vector<int>(w,0));

  auto dfs=
    MFP([&](auto dfs,int y,int x)->void{
          used[y][x]=1;
          if(y  >0&&st[y-1][x]!='#'&&!used[y-1][x]) dfs(y-1,x);
          if(y+1<h&&st[y+1][x]!='#'&&!used[y+1][x]) dfs(y+1,x);
          if(x  >0&&st[y][x-1]!='#'&&!used[y][x-1]) dfs(y,x-1);
          if(x+1<w&&st[y][x+1]!='#'&&!used[y][x+1]) dfs(y,x+1);
        });

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='s') dfs(i,j);

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='g')
        cout<<(used[i][j]?"Yes":"No")<<endl;
  return 0;
}
/*
  https://atcoder.jp/contests/atc001/tasks/dfs_a
*/
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T,typename U, typename H=hash<T> >
using gmap = cc_hash_table<T, U, H>;
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed AGC023_A(){
  using ll = long long;
  int n;
  scanf("%d",&n);
  vector<ll> as(n);
  for(int i=0;i<n;i++) scanf("%lld",&as[i]);

  gmap<ll, ll> mp;
  ll ans=0,sum=0;
  mp[sum]++;
  for(int i=0;i<n;i++){
    sum+=as[i];
    ans+=mp[sum];
    mp[sum]++;
  }

  printf("%lld\n",ans);
  return 0;
}
/*
  verified on 2019/12/09
  https://atcoder.jp/contests/agc023/tasks/agc023_a
*/

signed main(){
  AGC023_A();
  return 0;
}
#endif

#undef call_from_test

template<typename T>
struct chash{
  uint64_t operator()(T x) const{
    uint64_t y(x);
    y += 0x9e3779b97f4a7c15;
    y = (y ^ (y >> 30)) * 0xbf58476d1ce4e5b9;
    y = (y ^ (y >> 27)) * 0x94d049bb133111eb;
    return y ^ (y >> 31);
  }
};

signed main(){
  using ll = long long;

  int n,m;
  cin>>n>>m;

  m++;
  vector<int> as(m),bs(m);
  for(int i=0;i<m;i++) cin>>as[i];
  for(int i=1;i<m;i++) cin>>bs[i];

  vector<ll> hs;
  MFP([&](auto dfs,int l,int r)->void{
        int x=lower_bound(as.begin(),as.end(),r)-as.begin();
        if(as[x-1]<=l&&r<=as[x]) return;
        hs.emplace_back(((ll)l<<31)|r);
        int m=(l+r)>>1;
        dfs(l,m);
        dfs(m,r);
      })(0,(1<<n));

  sort(hs.begin(),hs.end());
  hs.erase(unique(hs.begin(),hs.end()),hs.end());

  gmap<ll, int, chash<ll> > idx;
  for(int i=0;i<(int)hs.size();i++) idx[hs[i]]=i;

  vector< vector<int> > dp(n+1,vector<int>(hs.size(),-1));

  int ans=(1<<n)-
    MFP([&](auto dfs,int l,int r,int d,int k)->int{
          int x=lower_bound(as.begin(),as.end(),r)-as.begin();
          if(as[x-1]<=l&&r<=as[x]){
            int v=bs[x],tmp=0;
            tmp+=(k==v);
            tmp+=(r-l)>>(n-v+1);
            return tmp;
          }

          if(~dp[k][idx[((ll)l<<31)|r]]) return dp[k][idx[((ll)l<<31)|r]];
          int &res=(dp[k][idx[((ll)l<<31)|r]]=0);

          int m=(l+r)>>1;
          res=max(res,dfs(l,m,d+1,d)+dfs(m,r,d+1,k));
          res=max(res,dfs(l,m,d+1,k)+dfs(m,r,d+1,d));
          return res;
        })(0,1<<n,1,0);

  cout<<ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 390
memory_kb: 32508
final_rank: 11

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2646"

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

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
#endif
//BEGIN CUT HERE
struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#endif
//BEGIN CUT HERE
template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  int h,w;
  cin>>h>>w;
  vector<string> st(h);
  for(int i=0;i<h;i++) cin>>st[i];

  vector<vector<int> > used(h,vector<int>(w,0));

  auto dfs=
    MFP([&](auto dfs,int y,int x)->void{
          used[y][x]=1;
          if(y  >0&&st[y-1][x]!='#'&&!used[y-1][x]) dfs(y-1,x);
          if(y+1<h&&st[y+1][x]!='#'&&!used[y+1][x]) dfs(y+1,x);
          if(x  >0&&st[y][x-1]!='#'&&!used[y][x-1]) dfs(y,x-1);
          if(x+1<w&&st[y][x+1]!='#'&&!used[y][x+1]) dfs(y,x+1);
        });

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='s') dfs(i,j);

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='g')
        cout<<(used[i][j]?"Yes":"No")<<endl;
  return 0;
}
/*
  https://atcoder.jp/contests/atc001/tasks/dfs_a
*/
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
template<typename T,typename U>
using gmap = cc_hash_table<T, U, hash<T> >;
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed AGC023_A(){
  using ll = long long;
  int n;
  scanf("%d",&n);
  vector<ll> as(n);
  for(int i=0;i<n;i++) scanf("%lld",&as[i]);

  gmap<ll, ll> mp;
  ll ans=0,sum=0;
  mp[sum]++;
  for(int i=0;i<n;i++){
    sum+=as[i];
    ans+=mp[sum];
    mp[sum]++;
  }

  printf("%lld\n",ans);
  return 0;
}
/*
  verified on 2019/12/09
  https://atcoder.jp/contests/agc023/tasks/agc023_a
*/

signed main(){
  AGC023_A();
  return 0;
}
#endif

#undef call_from_test

signed main(){
  using ll = long long;

  int n,m;
  cin>>n>>m;

  m++;
  vector<int> as(m),bs(m);
  for(int i=0;i<m;i++) cin>>as[i];
  for(int i=1;i<m;i++) cin>>bs[i];

  vector<ll> hs;
  MFP([&](auto dfs,int l,int r)->void{
        int x=lower_bound(as.begin(),as.end(),r)-as.begin();
        if(as[x-1]<=l&&r<=as[x]) return;
        hs.emplace_back(((ll)l<<31)|r);
        int m=(l+r)>>1;
        dfs(l,m);
        dfs(m,r);
      })(0,(1<<n));

  sort(hs.begin(),hs.end());
  hs.erase(unique(hs.begin(),hs.end()),hs.end());
  map<ll, int> idx;
  for(int i=0;i<(int)hs.size();i++) idx[hs[i]]=i;

  vector<vector<int> > dp(n+1,vector<int>(hs.size(),-1));

  int ans=(1<<n)-
    MFP([&](auto dfs,int l,int r,int d,int k)->int{
          int x=lower_bound(as.begin(),as.end(),r)-as.begin();
          if(as[x-1]<=l&&r<=as[x]){
            int v=bs[x],tmp=0;
            tmp+=(k==v);
            tmp+=(r-l)>>(n-v+1);
            return tmp;
          }

          if(~dp[k][idx[((ll)l<<31)|r]]) return dp[k][idx[((ll)l<<31)|r]];
          int &res=(dp[k][idx[((ll)l<<31)|r]]=0);

          int m=(l+r)>>1;
          res=max(res,dfs(l,m,d+1,d)+dfs(m,r,d+1,k));
          res=max(res,dfs(l,m,d+1,k)+dfs(m,r,d+1,d));
          return res;
        })(0,1<<n,1,0);

  cout<<ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 1490
memory_kb: 33404
final_rank: 18

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2646"

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

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
#endif
//BEGIN CUT HERE
struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#endif
//BEGIN CUT HERE
template<typename F>
struct FixPoint : F{
  FixPoint(F&& f):F(forward<F>(f)){}
  template<typename... Args>
  decltype(auto) operator()(Args&&... args) const{
    return F::operator()(*this,forward<Args>(args)...);
  }
};
template<typename F>
inline decltype(auto) MFP(F&& f){
  return FixPoint<F>{forward<F>(f)};
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed main(){
  int h,w;
  cin>>h>>w;
  vector<string> st(h);
  for(int i=0;i<h;i++) cin>>st[i];

  vector<vector<int> > used(h,vector<int>(w,0));

  auto dfs=
    MFP([&](auto dfs,int y,int x)->void{
          used[y][x]=1;
          if(y  >0&&st[y-1][x]!='#'&&!used[y-1][x]) dfs(y-1,x);
          if(y+1<h&&st[y+1][x]!='#'&&!used[y+1][x]) dfs(y+1,x);
          if(x  >0&&st[y][x-1]!='#'&&!used[y][x-1]) dfs(y,x-1);
          if(x+1<w&&st[y][x+1]!='#'&&!used[y][x+1]) dfs(y,x+1);
        });

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='s') dfs(i,j);

  for(int i=0;i<h;i++)
    for(int j=0;j<w;j++)
      if(st[i][j]=='g')
        cout<<(used[i][j]?"Yes":"No")<<endl;
  return 0;
}
/*
  https://atcoder.jp/contests/atc001/tasks/dfs_a
*/
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}
#endif
//BEGIN CUT HERE
template<typename T>
vector<T> convert_base(T x,T b){
  vector<T> res;
  T t=1,k=abs(b);
  while(x){
    res.emplace_back((x*t)%k);
    if(res.back()<0) res.back()+=k;
    x-=res.back()*t;
    x/=k;
    t*=b/k;
  }
  if(res.empty()) res.emplace_back(0);
  reverse(res.begin(),res.end());
  return res;
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed ABC105_C(){
  long long p;
  cin>>p;
  auto ans=convert_base(p,-2LL);
  for(auto x:ans) cout<<x;
  cout<<endl;
  return 0;
}
/*
  verified on 2019/03/31
  https://atcoder.jp/contests/abc105/tasks/abc105_c
*/

signed YUKI_499(){
  long long p;
  cin>>p;
  auto ans=convert_base(p,7LL);
  for(auto x:ans) cout<<x;
  cout<<endl;
  return 0;
}
/*
  verified on 2019/03/31
  https://yukicoder.me/problems/no/499
*/

signed YUKI_782(){
  long long t,b;
  cin>>t>>b;
  while(t--){
    long long p;
    cin>>p;
    auto ans=convert_base(p,b);
    for(auto x:ans) cout<<x;
    cout<<endl;
  }
  return 0;
}
/*
  verified on 2019/03/31
  https://yukicoder.me/problems/no/782
*/

signed main(){
  //ABC105_C();
  //YUKI_499();
  //YUKI_782();
  return 0;
}
#endif

#undef call_from_test

signed main(){
  using ll = long long;

  int n,m;
  cin>>n>>m;

  m++;
  vector<int> as(m),bs(m);
  for(int i=0;i<m;i++) cin>>as[i];
  for(int i=1;i<m;i++) cin>>bs[i];

  vector<ll> hs;
  MFP([&](auto dfs,int l,int r)->void{
        int x=lower_bound(as.begin(),as.end(),r)-as.begin();
        if(as[x-1]<=l&&r<=as[x]) return;
        hs.emplace_back(((ll)l<<31)|r);
        int m=(l+r)>>1;
        dfs(l,m);
        dfs(m,r);
      })(0,(1<<n));

  sort(hs.begin(),hs.end());
  hs.erase(unique(hs.begin(),hs.end()),hs.end());
  unordered_map<ll, int> idx;
  for(int i=0;i<(int)hs.size();i++) idx[hs[i]]=i;

  vector<vector<int> > dp(n+1,vector<int>(hs.size(),-1));

  int ans=(1<<n)-
    MFP([&](auto dfs,int l,int r,int d,int k)->int{
          int x=lower_bound(as.begin(),as.end(),r)-as.begin();
          if(as[x-1]<=l&&r<=as[x]){
            int v=bs[x],tmp=0;
            tmp+=(k==v);
            tmp+=(r-l)>>(n-v+1);
            return tmp;
          }

          if(~dp[k][idx[((ll)l<<31)|r]]) return dp[k][idx[((ll)l<<31)|r]];
          int &res=(dp[k][idx[((ll)l<<31)|r]]=0);

          int m=(l+r)>>1;
          res=max(res,dfs(l,m,d+1,d)+dfs(m,r,d+1,k));
          res=max(res,dfs(l,m,d+1,k)+dfs(m,r,d+1,d));
          return res;
        })(0,1<<n,1,0);

  cout<<ans<<endl;
  return 0;
}
accuracy: 1
time_ms: 540
memory_kb: 30488
final_rank: 12

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<math.h>
#include<complex>
#include<queue>

using namespace std;
#define rep(i,n) for(int i = 0 ; i < n ; ++i)
using ll = long long;
const ll inf = 1ll<<32;

int n,m;
vector<ll> a,b;

vector<ll> solve(int k, int l, int r){
    int nxt = *upper_bound(a.begin(),a.end(),l);
    vector<ll> ret(n+1,inf);
    if(nxt<r){
        auto vl = solve(k+1,l,(l+r)/2);
        auto vr = solve(k+1,(l+r)/2,r);
        rep(i,n+1){
            ret[i]=min(ret[i],vl[i]+vr[k]);
            ret[i]=min(ret[i],vl[k]+vr[i]);
        }
    }
    else {
        int idx = upper_bound(a.begin(),a.end(),l) - a.begin();
        --idx;
        int cur = b[idx];
        ll res = 0;
        int sz = 0;
        while((1ll<<sz)<r-l){
            if(k+sz!=cur)res += 1ll<<sz;
            ++sz;
        }
        rep(i,n+1){
            ret[i]=res;
            if(cur!=i)++ret[i];
        }
    }
    return ret;
}
 
int main(){
    cin>>n>>m;
    a.resize(m+1);
    b.resize(m);
    rep(i,m+1){
        cin>>a[i];
    }
    rep(i,m)cin>>b[i];
    auto ans = solve(1,0,1<<n);
    cout<<ans[0]<<endl;
}
accuracy: 1
time_ms: 30
memory_kb: 3228
final_rank: 7

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

using pii = pair<int, int>;

int main() {
    int n, m; cin >> n >> m;
    vector<int> a(m + 1), b(m);
    for(auto& x : a) cin >> x;
    for(auto& x : b) cin >> x;

    vector<map<pii, int>> dp(n + 1);
    // consider ['l', 'r'), 'd' is depth, 'final_rank' represents this block winner's rank (2^r)
    function<int(int, int, int, int)> solve = [&] (int l, int r, int d, int final_rank) {
        if(final_rank == d && dp[final_rank].count({l, r})) return dp[final_rank][{l, r}];
        const int i = lower_bound(begin(a), end(a), r) - begin(a) - 1;
        int res = 0;
        if(0 <= i && a[i] <= l && r <= a[i + 1]) { // contain completely
            if(b[i] >= d + 1) {
                res = r - l - (r - l) / (1 << (n - b[i] + 1));
            } else {
                res = r - l - (b[i] == final_rank);
            }
        } else { // choose which block win
            const int mid = (l + r) / 2;
            res = min(solve(l, mid, d + 1, final_rank) + solve(mid, r, d + 1, d + 1),
                      solve(l, mid, d + 1, d + 1) + solve(mid, r, d + 1, final_rank));
        }
        if(final_rank == d) return dp[final_rank][{l, r}] = res;
        else return res;
    };

    cout << solve(0, 1 << n, 0, 0) << endl;
}
accuracy: 1
time_ms: 940
memory_kb: 22236
final_rank: 16

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = signed;
using ll = long long;
signed main(){  
  cin.tie(0);
  ios::sync_with_stdio(0);
   
  Int n,m;
  cin>>n>>m;
 
  m++;
  vector<Int> a(m),b(m);
  for(Int i=0;i<m;i++) cin>>a[i];
  for(Int i=1;i<m;i++) cin>>b[i];
 
  vector<ll> hs;
  function<void(Int, Int)> predfs=[&](Int l,Int r){
    Int x=lower_bound(a.begin(),a.end(),r)-a.begin();
    if(a[x-1]<=l&&r<=a[x]) return;
     
    hs.emplace_back(((ll)l<<31)|r);
    Int m=(l+r)>>1;
    predfs(l,m);
    predfs(m,r);
  };
 
  predfs(0,(1<<n));
  sort(hs.begin(),hs.end());
  hs.erase(unique(hs.begin(),hs.end()),hs.end());
  unordered_map<ll, Int> idx;
  for(Int i=0;i<(Int)hs.size();i++) idx[hs[i]]=i;
  //cout<<hs.size()<<endl;
   
  vector<vector<Int> > dp(n+1,vector<Int>(hs.size(),-1));
   
  function<Int(Int, Int, Int, Int)> dfs=[&](Int l,Int r,Int d,Int k)->Int{
    //cout<<l<<" "<<r<<" "<<d<<" "<<k<<endl;
    Int x=lower_bound(a.begin(),a.end(),r)-a.begin();
    if(a[x-1]<=l&&r<=a[x]){
      Int v=b[x],tmp=0;
      tmp+=(k==v);
      tmp+=(r-l)>>(n-v+1);
      return tmp;
    }
 
    if(~dp[k][idx[((ll)l<<31)|r]]) return dp[k][idx[((ll)l<<31)|r]];
    Int &res=(dp[k][idx[((ll)l<<31)|r]]=0);
     
    Int m=(l+r)>>1;
    res=max(res,dfs(l,m,d+1,d)+dfs(m,r,d+1,k));
    res=max(res,dfs(l,m,d+1,k)+dfs(m,r,d+1,d));
    return res;
  };
   
  cout<<(1<<n)-dfs(0,1<<n,1,0)<<endl;
  return 0;
}
accuracy: 1
time_ms: 550
memory_kb: 30556
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = signed;
using ll = long long;
signed main(){  
  cin.tie(0);
  ios::sync_with_stdio(0);
   
  Int n,m;
  cin>>n>>m;
 
  m++;
  vector<Int> a(m),b(m);
  for(Int i=0;i<m;i++) cin>>a[i];
  for(Int i=1;i<m;i++) cin>>b[i];
 
  vector<ll> hs;
  function<void(Int, Int)> predfs=[&](Int l,Int r){
    Int x=lower_bound(a.begin(),a.end(),r)-a.begin();
    if(a[x-1]<=l&&r<=a[x]) return;
     
    hs.emplace_back(((ll)l<<31)|r);
    Int m=(l+r)>>1;
    predfs(l,m);
    predfs(m,r);
  };
 
  predfs(0,(1<<n));
  sort(hs.begin(),hs.end());
  hs.erase(unique(hs.begin(),hs.end()),hs.end());
  map<ll, Int> idx;
  for(Int i=0;i<(Int)hs.size();i++) idx[hs[i]]=i;
  //cout<<hs.size()<<endl;
   
  vector<vector<Int> > dp(n+1,vector<Int>(hs.size(),-1));
   
  function<Int(Int, Int, Int, Int)> dfs=[&](Int l,Int r,Int d,Int k)->Int{
    //cout<<l<<" "<<r<<" "<<d<<" "<<k<<endl;
    Int x=lower_bound(a.begin(),a.end(),r)-a.begin();
    if(a[x-1]<=l&&r<=a[x]){
      Int v=b[x],tmp=0;
      tmp+=(k==v);
      tmp+=(r-l)>>(n-v+1);
      return tmp;
    }
 
    if(~dp[k][idx[((ll)l<<31)|r]]) return dp[k][idx[((ll)l<<31)|r]];
    Int &res=(dp[k][idx[((ll)l<<31)|r]]=0);
     
    Int m=(l+r)>>1;
    res=max(res,dfs(l,m,d+1,d)+dfs(m,r,d+1,k));
    res=max(res,dfs(l,m,d+1,k)+dfs(m,r,d+1,d));
    return res;
  };
   
  cout<<(1<<n)-dfs(0,1<<n,1,0)<<endl;
  return 0;
}
accuracy: 1
time_ms: 1410
memory_kb: 33256
final_rank: 17