Problem:
ぬいぐるみの整理 (Plush Toys)
問題
ある JOI 関係者は，おもちゃ屋で働いている．今日は，店内にあるぬいぐるみコーナーの整理をすることになった．
ぬいぐるみコーナーの棚には，N 個のぬいぐるみが左から右に一列に並べられている．棚は仕切りにより N 個の区画に区切られており，1 つの区画に 1 個のぬいぐるみを置く．このおもちゃ屋は合計 M 種類のぬいぐるみを売っており，それぞれ 1 から M までの番号が付けられている．棚に並べられた N 個のぬいぐるみは，それぞれこの M 種類のうちのいずれかである．また，それぞれの種類のぬいぐるみは，少なくとも 1 個は存在する．
見栄えを良くするため，同じ種類のぬいぐるみが全て連続して棚に置かれるように，ぬいぐるみを並べ替えたい．次のような方法で，ぬいぐるみを並べ替えることにした．
N 個のぬいぐるみのうちいくつかを選び，棚から取り出す．取り出さなかったぬいぐるみの位置は動かさない．
取り出したぬいぐるみを，好きな順に棚の空いている区画に戻していく．
並べ替えた後，同じ種類のぬいぐるみが全て連続して棚に置かれていなければならない．
並べ替えるために取り出すぬいぐるみの個数の最小値を求めるプログラムを作成せよ．
入力
入力は 1 + N 行からなる．
1 行目には 2 個の整数 N, M (1 ≦ N ≦ 100000, 1 ≦ M ≦ 20) が空白を区切りとして書かれており，ぬいぐるみが N 個あり，種類が M 種類あることを表す．
続く N 行のそれぞれには，1 以上 M 以下の整数が書かれている． N 行のうちの i 行目 (1 ≦ i ≦ N) に書かれた整数は，棚の左から i 番目の区画に置かれたぬいぐるみの種類を表す．各種類について，少なくとも 1 個のぬいぐるみが存在していることが保証される．
出力
並べ替えるために取り出すぬいぐるみの個数の最小値を 1 行で出力せよ．
入出力例
入力例 1
7 2
1
2
2
2
1
2
1
出力例 1
2
入力例 2
12 4
1
3
2
4
2
1
2
3
1
1
3
4
出力例 2
7
入力例 1 においては，最初に置かれているぬいぐるみの種類は左から順に 1， 2， 2， 2， 1， 2， 1 である．並べ替えるために取り出すぬいぐるみの個数を最小にするには，左から 1 番目と 6 番目のぬいぐるみを取り出し，左から 1 番目に種類 2 のぬいぐるみを，左から 6 番目に種類 1 のぬいぐるみを配置すればよい．このとき，取り出すぬいぐるみの個数は 2 個である．
情報オリンピック日本委員会作 『第 16 回日本情報オリンピック JOI 2016/2017 予選競技課題』

Submitted solutions:

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define ALL(a)  a.begin(),a.end()
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))
#define FOR(i, s, e) for (int(i) = (s); (i) < (e); (i)++)
#define debug(x) cerr << #x << ": " << x << endl

using LL = long long; template<class T> using V = vector<T>;



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

	int N, M; cin >> N >> M;
	V<int>toy(N);
	FOR(i, 0, N) {
		cin >> toy[i]; toy[i]--;
	}

	// pre
	V<V<int>>pinfo(M, V<int>(N + 1, 0));
	FOR(i, 0, N) {
		pinfo[toy[i]][i+1]++;
	}
	FOR(i, 0, M) {
		FOR(j, 0, N) {
			pinfo[i][j + 1] += pinfo[i][j];
		}
	}

	// bitdp[state][ketu]:= 先頭から決定していったときに
	// stateを配置したとき最後がketuの最小の個数

	// 
	const int INF = 1e9;
	V<V<int>>bitdp(1 << M,V<int>(M,INF));
	bitdp[0][0] = 0;
	FOR(i, 0, M) {
		int LEN = pinfo[i][N];
		bitdp[1 << i][i] = pinfo[i][N]- pinfo[i][LEN];
	}
	FOR(state, 0, 1 << M) {
		FOR(i, 0, M) {
			if (!(state & 1 << i))continue;
			if (bitdp[state][i] == INF)continue;
			FOR(k, 0, M) {
				if (state & 1 << k)continue;
				int LEN = 0;
				FOR(yet, 0, M)if (state & 1 << yet)LEN += pinfo[yet][N];
				int addlen =  pinfo[k][N];
				// LEN + [0/1] = LEN + addlen
				int cost = addlen-(pinfo[k][LEN+addlen] - pinfo[k][LEN]);
				// cost = LEN - pinfo[k][LEN]
				int nx = state | (1 << k);
				bitdp[nx][k] = min(bitdp[nx][k], bitdp[state][i] + cost);
			}
		}
	}

	int ans = INF;
	FOR(i, 0, M) {
		ans = min(ans, bitdp[(1 << M) - 1][i]);
	}
	cout << ans << endl;

	return 0;
}
accuracy: 1
time_ms: 1710
memory_kb: 134136
final_rank: 17

code_snippet: #line 1 "a.cpp"
#define PROBLEM ""
#line 1 "/home/kuhaku/home/github/algo/lib/data_structure/wavelet_matrix.hpp"
#include <cassert>
#include <tuple>
#include <vector>
#line 2 "/home/kuhaku/home/github/algo/lib/data_structure/bit_vector.hpp"

/**
 * @brief 完備辞書
 *
 * @see https://ei1333.github.io/library/structure/wavelet/succinct-indexable-dictionary.hpp
 */
struct bit_vector {
    bit_vector() = default;
    bit_vector(unsigned int _length)
        : length(_length), blocks((_length + 31) >> 5), bit((_length + 31) >> 5),
          sum((_length + 31) >> 5) {}

    void set(unsigned int k) { bit[k >> 5] |= 1U << (k & 31); }

    void build() {
        sum[0] = 0U;
        for (unsigned int i = 1; i < blocks; ++i) {
            sum[i] = sum[i - 1] + __builtin_popcount(bit[i - 1]);
        }
    }

    bool operator[](unsigned int k) const { return bit[k >> 5] >> (k & 31) & 1; }

    unsigned int rank(unsigned int k) const {
        return sum[k >> 5] + __builtin_popcount(bit[k >> 5] & ((1U << (k & 31)) - 1));
    }
    unsigned int rank(bool val, unsigned int k) const { return val ? rank(k) : k - rank(k); }

    unsigned int select(unsigned int k) const {
        unsigned int sl = 0, sr = blocks + 1;
        while (sr - sl > 1) {
            unsigned int m = (sl + sr) >> 1;
            if (sum[m] < k) sl = m;
            else sr = m;
        }
        k -= sum[sl];
        unsigned int bl = 0, br = 32;
        while (br - bl > 1) {
            unsigned int m = (bl + br) >> 1;
            if (__builtin_popcount(bit[sl] & ((1U << m) - 1)) < k) bl = m;
            else br = m;
        }
        return (sl << 5) + bl;
    }

  private:
    unsigned int length, blocks;
    std::vector<unsigned int> bit, sum;
};
#line 5 "/home/kuhaku/home/github/algo/lib/data_structure/wavelet_matrix.hpp"

/**
 * @brief ウェーブレット行列
 * @see https://ei1333.github.io/library/structure/wavelet/wavelet-matrix.hpp
 *
 * @tparam T
 * @tparam L
 */
template <class T, int L = 20>
struct wavelet_matrix {
    wavelet_matrix() = default;
    wavelet_matrix(std::vector<T> v) : length(v.size()) {
        std::vector<T> l(length), r(length);
        for (int level = L - 1; level >= 0; --level) {
            matrix[level] = bit_vector(length + 1);
            int left = 0, right = 0;
            for (int i = 0; i < length; ++i) {
                if (v[i] >> level & 1) {
                    matrix[level].set(i);
                    r[right++] = v[i];
                } else {
                    l[left++] = v[i];
                }
            }
            mid[level] = left;
            matrix[level].build();
            v.swap(l);
            for (int i = 0; i < right; ++i) v[left + i] = r[i];
        }
    }

    T access(int k) const {
        T res = 0;
        for (int level = L - 1; level >= 0; --level) {
            bool f = matrix[level][k];
            if (f) res |= T(1) << level;
            k = matrix[level].rank(f, k) + mid[level] * f;
        }
        return res;
    }
    T operator[](int k) const { return access(k); }

    /**
     * @brief count i s.t. (0 <= i < r) && v[i] == x
     *
     * @param x
     * @param r
     * @return int
     */
    int rank(int r, T x) const {
        int l = 0;
        for (int level = L - 1; level >= 0; --level) {
            std::tie(l, r) = succ((x >> level) & 1, l, r, level);
        }
        return r - l;
    }

    /**
     * @brief count i s.t. (l <= i < r) && v[i] == x
     *
     * @param l
     * @param r
     * @param x
     * @return int
     */
    int rank(int l, int r, T x) const { return rank(r, x) - rank(l, x); }

    /**
     * @brief k-th smallest number in v[l ... r-1]
     *
     * @param l
     * @param r
     * @param k
     * @return T
     */
    T kth_smallest(int l, int r, int k) const {
        assert(0 <= k && k < r - l);
        T res = 0;
        for (int level = L - 1; level >= 0; --level) {
            int cnt = matrix[level].rank(false, r) - matrix[level].rank(false, l);
            bool f = cnt <= k;
            if (f) {
                res |= T(1) << level;
                k -= cnt;
            }
            std::tie(l, r) = succ(f, l, r, level);
        }
        return res;
    }

    /**
     * @brief k-th largest number in v[l ... r-1]
     *
     * @param l
     * @param r
     * @param k
     * @return T
     */
    T kth_largest(int l, int r, int k) const { return kth_smallest(l, r, r - l - k - 1); }

    /**
     * @brief count i s.t. (l <= i < r) && (v[i] < upper)
     *
     * @param l
     * @param r
     * @param upper
     * @return int
     */
    int range_freq(int l, int r, T upper) const {
        int res = 0;
        for (int level = L - 1; level >= 0; --level) {
            bool f = ((upper >> level) & 1);
            if (f) res += matrix[level].rank(false, r) - matrix[level].rank(false, l);
            std::tie(l, r) = succ(f, l, r, level);
        }
        return res;
    }

    /**
     * @brief count i s.t. (l <= i < r) && (lower <= v[i] < upper)
     *
     * @param l
     * @param r
     * @param lower
     * @param upper
     * @return int
     */
    int range_freq(int l, int r, T lower, T upper) const {
        return range_freq(l, r, upper) - range_freq(l, r, lower);
    }

    /**
     * @brief max v[i] s.t. (l <= i < r) && (v[i] < upper)
     *
     * @param l
     * @param r
     * @param upper
     * @return T
     */
    T prev_value(int l, int r, T upper) const {
        int cnt = range_freq(l, r, upper);
        return cnt == 0 ? T(-1) : kth_smallest(l, r, cnt - 1);
    }

    /**
     * @brief min v[i] s.t. (l <= i < r) && (lower <= v[i])
     *
     * @param l
     * @param r
     * @param lower
     * @return T
     */
    T next_value(int l, int r, T lower) const {
        int cnt = range_freq(l, r, lower);
        return cnt == r - l ? T(-1) : kth_smallest(l, r, cnt);
    }

  private:
    int length;
    bit_vector matrix[L];
    int mid[L];

    std::pair<int, int> succ(bool f, int l, int r, int level) const {
        return {matrix[level].rank(f, l) + mid[level] * f,
                matrix[level].rank(f, r) + mid[level] * f};
    }
};
#line 2 "/home/kuhaku/home/github/algo/lib/template/template.hpp"
#pragma GCC target("sse4.2,avx2,bmi2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
template <class T, class U>
constexpr bool chmax(T &a, const U &b) {
    return a < (T)b ? a = (T)b, true : false;
}
template <class T, class U>
constexpr bool chmin(T &a, const U &b) {
    return (T)b < a ? a = (T)b, true : false;
}
constexpr std::int64_t INF = 1000000000000000003;
constexpr int Inf = 1000000003;
constexpr double EPS = 1e-7;
constexpr double PI = M_PI;
#line 3 "/home/kuhaku/home/github/algo/lib/template/macro.hpp"
#define FOR(i, m, n) for (int i = (m); i < int(n); ++i)
#define FORR(i, m, n) for (int i = (m)-1; i >= int(n); --i)
#define FORL(i, m, n) for (int64_t i = (m); i < int64_t(n); ++i)
#define rep(i, n) FOR (i, 0, n)
#define repn(i, n) FOR (i, 1, n + 1)
#define repr(i, n) FORR (i, n, 0)
#define repnr(i, n) FORR (i, n + 1, 1)
#define all(s) (s).begin(), (s).end()
#line 3 "/home/kuhaku/home/github/algo/lib/template/sonic.hpp"
struct Sonic {
    Sonic() {
        std::ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        std::cout << std::fixed << std::setprecision(20);
    }

    constexpr void operator()() const {}
} sonic;
#line 5 "/home/kuhaku/home/github/algo/lib/template/atcoder.hpp"
using namespace std;
using ll = std::int64_t;
using ld = long double;
template <class T, class U>
std::istream &operator>>(std::istream &is, std::pair<T, U> &p) {
    return is >> p.first >> p.second;
}
template <class T>
std::istream &operator>>(std::istream &is, std::vector<T> &v) {
    for (T &i : v) is >> i;
    return is;
}
template <class T, class U>
std::ostream &operator<<(std::ostream &os, const std::pair<T, U> &p) {
    return os << '(' << p.first << ',' << p.second << ')';
}
template <class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
    for (auto it = v.begin(); it != v.end(); ++it) {
        os << (it == v.begin() ? "" : " ") << *it;
    }
    return os;
}
template <class Head, class... Tail>
void co(Head &&head, Tail &&...tail) {
    if constexpr (sizeof...(tail) == 0) std::cout << head << '\n';
    else std::cout << head << ' ', co(std::forward<Tail>(tail)...);
}
template <class Head, class... Tail>
void ce(Head &&head, Tail &&...tail) {
    if constexpr (sizeof...(tail) == 0) std::cerr << head << '\n';
    else std::cerr << head << ' ', ce(std::forward<Tail>(tail)...);
}
template <typename T, typename... Args>
auto make_vector(T x, int arg, Args... args) {
    if constexpr (sizeof...(args) == 0) return std::vector<T>(arg, x);
    else return std::vector(arg, make_vector<T>(x, args...));
}
void Yes(bool is_correct = true) {
    std::cout << (is_correct ? "Yes" : "No") << '\n';
}
void No(bool is_not_correct = true) {
    Yes(!is_not_correct);
}
void YES(bool is_correct = true) {
    std::cout << (is_correct ? "YES" : "NO") << '\n';
}
void NO(bool is_not_correct = true) {
    YES(!is_not_correct);
}
void Takahashi(bool is_correct = true) {
    std::cout << (is_correct ? "Takahashi" : "Aoki") << '\n';
}
void Aoki(bool is_not_correct = true) {
    Takahashi(!is_not_correct);
}
#line 3 "/home/kuhaku/home/github/algo/lib/template/vector.hpp"

struct increment_impl {
    template <class T>
    const increment_impl &operator>>(std::vector<T> &v) const {
        for (auto &x : v) ++x;
        return *this;
    }
} Inc;

struct decrement_impl {
    template <class T>
    const decrement_impl &operator>>(std::vector<T> &v) const {
        for (auto &x : v) --x;
        return *this;
    }
} Dec;

struct sort_impl {
    template <class T>
    const sort_impl &operator>>(std::vector<T> &v) const {
        std::sort(v.begin(), v.end());
        return *this;
    }
} Sort;

struct unique_impl {
    template <class T>
    const unique_impl &operator>>(std::vector<T> &v) const {
        std::sort(v.begin(), v.end());
        v.erase(std::unique(v.begin(), v.end()), v.end());
        return *this;
    }
} Uniq;
#line 5 "a.cpp"

int main(void) {
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    cin >> a;
    Dec >> a;
    vector<int> s(m);
    for (auto x : a) ++s[x];
    wavelet_matrix wm(a);
    vector<int> dp(1 << m, Inf);
    dp[0] = 0;
    rep (bit, 1 << m) {
        int sum = 0;
        rep (i, m) {
            if (bit >> i & 1)
                sum += s[i];
        }
        rep (i, m) {
            if (bit >> i & 1)
                continue;
            chmin(dp[bit | (1 << i)], dp[bit] + s[i] - wm.rank(sum, sum + s[i], i));
        }
    }
    co(dp.back());

    return 0;
}
accuracy: 1
time_ms: 1750
memory_kb: 7860
final_rank: 13

code_snippet: #include <iostream>
#include <vector>

using namespace std;

int main() {
	int n, m;
	cin >> n >> m;
	vector<int> a(n);
	for (int &e : a) cin >> e;

	vector<vector<int>> cnt(m, vector<int>(n + 1));
	for (int i = 0; i < m; ++i) {
		for (int j = 0; j < n; ++j) cnt[i][j + 1] = cnt[i][j] + (a[j] == i + 1);
	}
	vector<int> sum(1 << m);
	for (int bit = 1; bit < (1 << m); ++bit) {
		for (int i = 0; i < m; ++i) {
			if (bit & (1 << i)) sum[bit] += cnt[i][n];
		}
	}

	vector<int> dp(1 << m, 1e9);
	dp[0] = 0;
	for (int bit = 0; bit < (1 << m); ++bit) {
		for (int i = 0; i < m; ++i) {
			if (bit & (1 << i)) continue;
			int l = sum[bit], r = sum[bit | (1 << i)];
			dp[bit | (1 << i)] =
				min(dp[bit | (1 << i)], dp[bit] + r - l - (cnt[i][r] - cnt[i][l]));
		}
	}
	cout << dp.back() << endl;

	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 19268
final_rank: 7

code_snippet: #include <iostream>
#include <vector>
#include <map>
using namespace std;

struct E{
	int point;
	int perm;
	bool operator<(const E &e)const{
		return perm<e.perm;
	}
};

vector<int> count,data,dp,ruiseki[21];
map<E,int> ms;

int f(){
	int n,m;
	cin>>n>>m;
	
	
	for(int i=0;i<=m;i++){
		count.push_back(0);
	}
	
	for(int i=0;i<=n;i++){
		int t=0;
		if(i==0){
			data.push_back(0);
		}else{
			cin>>t;
			data.push_back(t);
			count[t]++;
		}
		dp.push_back(-1);
		for(int j=1;j<=m;j++){
			if(i==0){
				ruiseki[j].push_back(0);
			}else{
				ruiseki[j].push_back(ruiseki[j][i-1]+(j==t?0:1));
			}
		}
	}
	E e;
	e.perm=0;
	e.point=0;
	ms[e]=0;
	for(int i=1;i<=m;i++){
		map<E,int> ms2;
		for(map<E,int>::iterator it=ms.begin();it!=ms.end();it++){
			E e=(*it).first;
			int ans=(*it).second;
			for(int j=1;j<=m;j++){
				int p1=1<<(j-1);
				if((e.perm&p1)>0)continue;
				E e2;
				e2.perm=(e.perm|p1);
				e2.point=e.point+count[j];
				int ans2=ans+ruiseki[j][e2.point]-ruiseki[j][e.point];
				if(ms2.find(e2)==ms2.end()||ms2[e2]>ans2){
					ms2[e2]=ans2;
				}
			}
		}
		ms.clear();
		ms.insert(ms2.begin(),ms2.end());
	}
	cout<<(*(ms.begin())).second<<endl;
	
	return 0;
}

int main() {
	f();
	return 0;
}
accuracy: 1
time_ms: 1640
memory_kb: 34696
final_rank: 16

code_snippet: #include <iostream>
#include <vector>
using namespace std;

int f(){
	int n,m;
	cin>>n>>m;
	vector<int> count,data,dp,ruiseki[21];
	
	for(int i=0;i<=m;i++){
		count.push_back(0);
	}
	
	for(int i=0;i<=n;i++){
		int t=0;
		if(i==0){
			data.push_back(0);
		}else{
			cin>>t;
			data.push_back(t);
			count[t]++;
		}
		dp.push_back(-1);
		for(int j=1;j<=m;j++){
			if(i==0){
				ruiseki[j].push_back(0);
			}else{
				ruiseki[j].push_back(ruiseki[j][i-1]+(j==t?0:1));
			}
		}
	}
	dp[0]=0;
	for(int i=0;i<n;i++){
		if(dp[i]==-1)continue;
		int c1=dp[i];
		for(int j=1;j<=m;j++){
			int p1=i+count[j];
			if(dp.size()<=p1)continue;
			int c2=c1+ruiseki[j][p1]-ruiseki[j][i];
			if(dp[p1]==-1||dp[p1]>c2){
				dp[p1]=c2;
			}
		}
	}
	cout<<dp[dp.size()-1]<<endl;
	
	
	return 0;
}

int main() {
	f();
	return 0;
}
accuracy: 0.4
time_ms: 10
memory_kb: 8020
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vll>;
using vvvll = vector<vvll>;
using vb = vector<bool>;
using vvb = vector<vb>;
using vvvb = vector<vvb>;
#define all(A) A.begin(),A.end()
#define rep(i, n) for (ll i = 0; i < (ll) (n); i++)
template<class T>
bool chmax(T& p, T q, bool C = 1) {
    if (C == 0 && p == q) {
        return 1;
    }
    if (p < q) {
        p = q;
        return 1;
    }
    else {
        return 0;
    }
}

template<class T>
bool chmin(T& p, T q, bool C = 1) {
    if (C == 0 && p == q) {
        return 1;
    }
    if (p > q) {
        p = q;
        return 1;
    }
    else {
        return 0;
    }
}

ll modPow(long long a, long long n, long long p) {
    if (n == 0) return 1; // 0乗にも対応する場合
    if (n == 1) return a % p;
    if (n % 2 == 1) return (a * modPow(a, n - 1, p)) % p;
    long long t = modPow(a, n / 2, p);
    return (t * t) % p;
}


ll gcd(ll(a), ll(b)) {
    if (a == 0)return b;
    if (b == 0)return a;
    ll c = a;
    while (a % b != 0) {
        c = a % b;
        a = b;
        b = c;
    }
    return b;
}
ll sqrtz(ll N) {
    ll L = 0;
    ll R = sqrt(N) + 10000;
    while (abs(R - L) > 1) {
        ll mid = (R + L) / 2;
        if (mid * mid <= N)L = mid;
        else R = mid;
    }
    return L;

}


int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    ll N,M;
    cin>>N>>M;
    vll A(N);
    rep(i,N)cin>>A[i],A[i]--;

    vll DP(1<<M,1e18);
    vvll B(M,vll(N+1,0));
    
    rep(i,N){
        rep(m,M){
            B[m][i+1]=B[m][i];
        }
        B[A[i]][i+1]++;
    }
    DP[0]=0;
    rep(bit,1<<M){
        ll s=0;
        rep(n,M){
            if(bit&(1<<n))s+=B[n][N];
        }

        rep(n,M){
            if(bit&(1<<n)){

            }
            else{
                ll d=B[n][N];
                chmin(DP[bit+(1<<n)],DP[bit]+d-(B[n][s+d]-B[n][s]));
            }
        }
    }
    cout<<DP[(1<<M)-1]<<endl;
    
}
accuracy: 1
time_ms: 130
memory_kb: 28332
final_rank: 12

code_snippet: #include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
#define INF (100000000)
typedef pair<int, int> P;
int main() {
  int N, M;
  cin >> N >> M;
  vector<int> D;
  vector<P> DPAIR(M);
  for (int i = 0; i < M; ++i)
    DPAIR[i] = P(i, 0);
  for (int i = 0; i < N; ++i) {
    int temp;
    cin >> temp;
    D.push_back(temp - 1);
    ++DPAIR[temp - 1].second;
  }
  vector<int> DD[M];
  for (int i = 0; i < M; ++i) {
    DD[i].resize(N);
    DD[i][0] = (D[0] == i ? 1 : 0);
    for (int j = 1; j < N; ++j) {
      DD[i][j] = DD[i][j - 1] + (D[j] == i ? 1 : 0);
    }
  }
  string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  string istr = ALPHA.substr(0, M);
  vector<int> indx(M + 1);
  map<string, P> mp;
  for (int c = 1; c <= M; ++c) {
    indx[c] = M;
    for (int i = 0; i < c; ++i)
      indx[i] = i;
    --indx[c - 1];
    while (indx[0] < M - c || c == M) {
      int now = c - 1;
      while (indx[0] != M - c || c == M) {
        if (indx[now + 1] - indx[now] > 1) {
          ++indx[now];
          break;
        } else if (indx[now] - indx[now - 1] > 1) {
          ++indx[now - 1];
          for (int i = now; i < c; ++i)
            indx[i] = indx[i - 1] + 1;
          break;
        } else {
          --now;
        }
      }
      int cnt = INF;
      int len;
      for (int i = 0; i < c; ++i) {
        string s = "";
        for (int j = 0; j < c; ++j) {
          if (j == i)
            continue;
          s.push_back(istr[indx[j]]);
        }
        if (s == "") {
          cnt = min(cnt, DPAIR[indx[i]].second -
                             DD[indx[i]][DPAIR[indx[i]].second - 1]);
          len = DPAIR[indx[i]].second;
        } else {
          int fst = mp[s].first;
          int snd = mp[s].second;
          cnt = min(cnt, fst + DPAIR[indx[i]].second -
                             DD[indx[i]][snd + DPAIR[indx[i]].second - 1] +
                             DD[indx[i]][snd - 1]);
          len = snd + DPAIR[indx[i]].second;
        }
      }
      string s = "";
      for (int i = 0; i < c; ++i) {
        s.push_back(istr[indx[i]]);
      }
      mp[s] = make_pair(cnt, len);
      if (c == M)
        break;
    }
  }
  cout << mp[istr].first << endl;
  return 0;
}
accuracy: 1
time_ms: 5130
memory_kb: 137952
final_rank: 19

code_snippet: #include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
#define INF (100000000)
typedef pair<int, int> P;
int main() {
  int N, M;
  cin >> N >> M;
  vector<int> D;
  vector<P> DPAIR(M);
  for (int i = 0; i < M; ++i)
    DPAIR[i] = P(i, 0);
  for (int i = 0; i < N; ++i) {
    int temp;
    cin >> temp;
    D.push_back(temp - 1);
    ++DPAIR[temp - 1].second;
  }
  vector<int> DD[M];
  for (int i = 0; i < M; ++i) {
    DD[i].resize(N);
    DD[i][0] = (D[0] == i ? 1 : 0);
    for (int j = 1; j < N; ++j) {
      DD[i][j] = DD[i][j - 1] + (D[j] == i ? 1 : 0);
    }
  }
  string ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  string istr = ALPHA.substr(0, M);
  vector<int> indx(M + 1);
  map<string, P> mp;
  for (int c = 1; c <= M; ++c) {
    indx[c] = M;
    for (int i = 0; i < c; ++i)
      indx[i] = i;
    --indx[c - 1];
    while (indx[0] < M - c || c == M) {
      int now = c - 1;
      while (indx[0] != M - c || c == M) {
        if (indx[now + 1] - indx[now] > 1) {
          ++indx[now];
          break;
        } else if (indx[now] - indx[now - 1] > 1) {
          ++indx[now - 1];
          for (int i = now; i < c; ++i)
            indx[i] = indx[i - 1] + 1;
          break;
        } else {
          --now;
        }
      }
      int cnt = INF;
      int len;
      string str = "";
      for (int j = 0; j < c; ++j) {
        str.push_back(istr[indx[j]]);
      }
      for (int i = 0; i < c; ++i) {
        string s = str;
        s.erase(s.begin() + i);
        if (s == "") {
          cnt = min(cnt, DPAIR[indx[i]].second -
                             DD[indx[i]][DPAIR[indx[i]].second - 1]);
          len = DPAIR[indx[i]].second;
        } else {
          int fst = mp[s].first;
          int snd = mp[s].second;
          cnt = min(cnt, fst + DPAIR[indx[i]].second -
                             DD[indx[i]][snd + DPAIR[indx[i]].second - 1] +
                             DD[indx[i]][snd - 1]);
          len = snd + DPAIR[indx[i]].second;
        }
      }
      mp[str] = make_pair(cnt, len);
      if (c == M)
        break;
    }
  }
  cout << mp[istr].first << endl;
  return 0;
}
accuracy: 1
time_ms: 3830
memory_kb: 138044
final_rank: 18

code_snippet: #include <algorithm>
#include <iostream>
using namespace std;
static const int MAX_N = 100000;
static const int MAX_M = 20;
int N, M;
int K[MAX_N];
int sum[MAX_M][MAX_N + 1];
int dp[1 << MAX_M];
int main() {
  cin >> N >> M;
  for (int i = 0; i < N; i++)
    cin >> K[i];
  fill(sum[0], sum[M], 0);
  for (int i = 0; i < N; i++)
    sum[K[i] - 1][i + 1]++;
  for (int i = 0; i < M; i++) {
    for (int j = 1; j <= N; j++) {
      sum[i][j] += sum[i][j - 1];
    }
  }
  fill(dp, dp + (1 << M), 0);
  for (int i = 1; i < (1 << M); i++) {
    int minimum_num = MAX_N + 1;
    for (int j = 0; j < M; j++) {
      if (!(i & (1 << j)))
        continue;
      int replaced_doll_num = 0;
      for (int k = 0; k < M; k++) {
        if (j == k)
          continue;
        if (i & (1 << k))
          replaced_doll_num += sum[k][N];
      }
      minimum_num =
          min(minimum_num, dp[i - (1 << j)] + sum[j][N] -
                               (sum[j][replaced_doll_num + sum[j][N]] -
                                sum[j][replaced_doll_num]));
    }
    dp[i] = minimum_num;
  }
  cout << dp[(1 << M) - 1] << endl;
  return 0;
}
accuracy: 1
time_ms: 440
memory_kb: 15416
final_rank: 9

code_snippet: #include <algorithm>
#include <iostream>
using namespace std;
static const int MAX_N = 100000;
static const int MAX_M = 20;
int N, M;
int K[MAX_N];
int sum[MAX_M][MAX_N + 1];
int dp[1 << MAX_M], dp2[1 << MAX_M];
int main() {
  cin >> N >> M;
  for (int i = 0; i < N; i++)
    cin >> K[i];
  fill(sum[0], sum[M], 0);
  for (int i = 0; i < N; i++)
    sum[K[i] - 1][i + 1]++;
  for (int i = 0; i < M; i++) {
    for (int j = 1; j <= N; j++) {
      sum[i][j] += sum[i][j - 1];
    }
  }
  fill(dp, dp + (1 << M), 0);
  fill(dp2, dp2 + (1 << M), 0);
  for (int i = 1; i < (1 << M); i++) {
    int minimum_num = MAX_N + 1;
    for (int j = 0; j < M; j++) {
      if (!(i & (1 << j)))
        continue;
      dp2[i] = dp2[i - (1 << j)] + sum[j][N];
      minimum_num =
          min(minimum_num, dp[i - (1 << j)] + sum[j][N] -
                               (sum[j][dp2[i - (1 << j)] + sum[j][N]] -
                                sum[j][dp2[i - (1 << j)]]));
    }
    dp[i] = minimum_num;
  }
  cout << dp[(1 << M) - 1] << endl;
  return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 19484
final_rank: 6

code_snippet: #define READ_FROM_FILE 0

#if READ_FROM_FILE
#include <fstream>
#endif

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


int main() {
#if READ_FROM_FILE
	ifstream ifs("test0.txt");
	cin.rdbuf(ifs.rdbuf());
#endif
	int n = 0;
	int m = 0;
	int tmp = 0;
	vector<int> shelf;
	vector<vector<int>> acc_sum_vec;
	unordered_map<int, int> dp;

	cin >> n >> m;

	for (int i = 0; i < n; i++) {
		cin >> tmp;
		shelf.emplace_back(tmp - 1);
	}

	for (int i = 0; i < m; i++) {
		vector<int> acc_sum(n + 1, 0);

		for (int j = 1; j < n + 1; j++) {
			if (shelf[j - 1] == i) {
				acc_sum[j] = 1;
			}
		}
		acc_sum_vec.emplace_back(acc_sum);
	}

	for (int i = 0; i < m; i++) {
		for (int j = 1; j < n + 1; j++) {
			acc_sum_vec[i][j] += acc_sum_vec[i][j - 1];
		}
	}
	
	dp[0] = 0;
	for (int i = 0; i < m; i++) {
		unordered_map<int, int> new_dp;

		for (unordered_map<int, int>::iterator it = dp.begin(); it != dp.end(); it++) {
			int state = it->first;
			int min_num_swapped_toys = it->second;

			for (int j = 0; j < m; j++) {
				if ((state & (1 << j)) == 0) {
					int n_state = state | (1 << j);
					int c_num_toys = 0;
					int p_num_toys = 0;

					for (int k = 0; k < m; k++) {
						if ((n_state & (1 << k)) > 0) {
							c_num_toys += acc_sum_vec[k].back();
						}
						if ((state & (1 << k)) > 0) {
							p_num_toys += acc_sum_vec[k].back();
						}
					}

					int num_swapped_toys = acc_sum_vec[j][p_num_toys] - acc_sum_vec[j][0] + acc_sum_vec[j].back() - acc_sum_vec[j][c_num_toys] + min_num_swapped_toys;

					if (new_dp.count(n_state) == 0) {
						new_dp[n_state] = num_swapped_toys;
					}
					else {
						new_dp[n_state] = min(new_dp[n_state], num_swapped_toys);
					}
				}
			}
		}
		dp = new_dp;
	}

	int min_num_swapped_toys = n + 1;
	for (unordered_map<int, int>::iterator it = dp.begin(); it != dp.end(); it++) {
		min_num_swapped_toys = min(min_num_swapped_toys, it->second);
	}
	cout << min_num_swapped_toys << endl;

	return 0;
}
accuracy: 1
time_ms: 1320
memory_kb: 26320
final_rank: 15

code_snippet: #define READ_FROM_FILE 0

#if READ_FROM_FILE
#include <fstream>
#endif

#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;


int main() {
#if READ_FROM_FILE
	ifstream ifs("test0.txt");
	cin.rdbuf(ifs.rdbuf());
#endif
	int n = 0;
	int m = 0;
	int tmp = 0;
	vector<int> shelf;
	vector<vector<int>> acc_sum_vec;
	unordered_map<int, int> dp;

	cin >> n >> m;

	for (int i = 0; i < n; i++) {
		cin >> tmp;
		shelf.emplace_back(tmp - 1);
	}

	for (int i = 0; i < m; i++) {
		vector<int> acc_sum(n + 1, 0);

		for (int j = 1; j < n + 1; j++) {
			if (shelf[j - 1] == i) {
				acc_sum[j] = 1;
			}
		}
		acc_sum_vec.emplace_back(acc_sum);
	}

	for (int i = 0; i < m; i++) {
		for (int j = 1; j < n + 1; j++) {
			acc_sum_vec[i][j] += acc_sum_vec[i][j - 1];
		}
	}
	
	dp[0] = 0;
	for (int i = 0; i < m; i++) {
		unordered_map<int, int> new_dp;

		for (unordered_map<int, int>::iterator it = dp.begin(); it != dp.end(); it++) {
			int state = it->first;
			int min_num_toys = it->second;

			for (int j = 0; j < m; j++) {
				if ((state & (1 << j)) == 0) {
					int n_state = state | (1 << j);
					int num_toys = 0;
					int p_num_toys = 0;

					for (int k = 0; k < m; k++) {
						if ((n_state & (1 << k)) > 0) {
							num_toys += acc_sum_vec[k].back();
						}
						if ((state & (1 << k)) > 0) {
							p_num_toys += acc_sum_vec[k].back();
						}
					}

					int num_swapped_toys = acc_sum_vec[j][p_num_toys] - acc_sum_vec[j][0] + acc_sum_vec[j].back() - acc_sum_vec[j][num_toys] + min_num_toys;

					if (new_dp.count(n_state) == 0) {
						new_dp[n_state] = num_swapped_toys;
					}
					else {
						new_dp[n_state] = min(new_dp[n_state], num_swapped_toys);
					}
				}
			}
		}
		dp = new_dp;
	}

	int min_num_toys = n + 1;

	for (unordered_map<int, int>::iterator it = dp.begin(); it != dp.end(); it++) {
		min_num_toys = min(min_num_toys, it->second);
	}
	cout << min_num_toys << endl;

	return 0;
}
accuracy: 1
time_ms: 1310
memory_kb: 26004
final_rank: 14

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

inline void chmin(i32& a, i32 b) {
    if (a > b) {
        a = b;
    }
}

const i32 supi = (1 << 30);

int main() {
    i32 n, m; cin >> n >> m;
    vector as(n, 0);
    for (auto& a : as) {
        cin >> a;
        a--;
    }
    vector sums = [&]() -> vector<vector<i32>> {
        vector res(m, vector(n + 1, 0));
        for (i32 i = 0 ; i < n ; i++) {
            res[as[i]][i + 1]++;
        }
        for (auto& r : res) {
            for (i32 i = 0 ; i + 1 < n + 1 ; i++) {
                r[i + 1] += r[i];
            }
        }
        return res;
    }();
    vector dp((1 << m), supi);
    dp[0] = 0;
    for (i32 bit = 0 ; bit < (1 << m) ; bit++) {
        assert(dp[bit] < supi);
        i32 used = 0;
        vector yet(0, 0);
        for (i32 i = 0 ; i < m ; i++) {
            if (bit & (1 << i)) {
                used += sums[i].back();
            }
            else {
                yet.push_back(i);
            }
        }
        for (auto i : yet) {
            i32 now = sums[i].back();
            i32 cnt = sums[i].back() - sums[i][used + now];
            for (auto j : yet) {
                if (i == j) {
                    continue;
                }
                cnt += sums[j][used + now] - sums[j][used];
            }
            chmin(dp[bit | (1 << i)], dp[bit] + cnt);
        }
    }
    cout << dp.back() << endl;
}
accuracy: 1
time_ms: 240
memory_kb: 15128
final_rank: 5

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 0633.cc: ぬいぐるみの整理 (Plush Toys)
 */

#include<cstdio>
#include<algorithm>
 
using namespace std;

/* constant */

const int MAX_N = 100000;
const int MAX_M = 20;
const int MBITS = 1 << MAX_M;
const int INF = 1 << 30;

/* typedef */

/* global variables */

int as[MAX_N], cs[MAX_M], css[MAX_N + 1][MAX_M];
int bsums[MBITS], dp[MBITS];

/* subroutines */

inline void setmin(int &a, int b) { if (a > b) a = b; }

/* main */

int main() {
  int n, m;
  scanf("%d%d", &n, &m);

  for (int i = 0; i < n; i++) {
    scanf("%d", as + i), as[i]--;
    cs[as[i]]++;
    copy(css[i], css[i] + m, css[i + 1]);
    css[i + 1][as[i]]++;
  }

  int mbits = 1 << m;

  bsums[0] = 0;
  for (int bits = 1, msb = 1, msi = 0; bits < mbits; bits++) {
    if ((msb << 1) <= bits) msb <<= 1, msi++;
    bsums[bits] = bsums[bits ^ msb] + cs[msi];
  }

  fill(dp, dp + mbits, INF);
  dp[0] = 0;

  for (int bits = 0; bits < mbits; bits++)
    for (int i = 0, bi = 1; i < m; i++, bi <<= 1)
      if (! (bits & bi)) {
	int l = css[bsums[bits | bi]][i] - css[bsums[bits]][i];
	setmin(dp[bits | bi], dp[bits] + cs[i] - l);
      }

  printf("%d\n", dp[mbits - 1]);

  return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 19332
final_rank: 4

code_snippet: #include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int sum[100001][20];
int dp[1<<20];
int main(){
	int n,m,a[100000];
	cin>>n>>m;
	for(int i=0;i<n;i++)
		cin>>a[i],a[i]--;
	for(int i=0;i<n;i++){
		copy(sum[i],sum[i]+m,sum[i+1]);
		sum[i+1][a[i]]++;
	}
	for(int S=1;S<1<<m;S++)
		dp[S]=1e9;
	for(int S=0;S<1<<m;S++){
		int tmp=0;
		for(int i=0;i<m;i++)
			if(S>>i&1)
				tmp+=sum[n][i];
		for(int i=0;i<m;i++)
			if(~S>>i&1)
				dp[S|1<<i]=min(dp[S|1<<i],dp[S]+sum[n][i]-(sum[tmp+sum[n][i]][i]-sum[tmp][i]));
	}
	cout<<dp[(1<<m)-1]<<endl;
}
accuracy: 1
time_ms: 80
memory_kb: 15624
final_rank: 1

code_snippet: #include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define drep(i,j,n) for(int i=0;i<(int)(n-1);i++)for(int j=i+1;j<(int)(n);j++)
#define trep(i,j,k,n) for(int i=0;i<(int)(n-2);i++)for(int j=i+1;j<(int)(n-1);j++)for(int k=j+1;k<(int)(n);k++)
#define codefor int test;scanf("%d",&test);while(test--)
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define yes(ans) if(ans)printf("yes\n");else printf("no\n")
#define Yes(ans) if(ans)printf("Yes\n");else printf("No\n")
#define YES(ans) if(ans)printf("YES\n");else printf("NO\n")
#define popcount(v) __builtin_popcountll(v)
#define vector2d(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define vector3d(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
using namespace std;
using ll = long long;
template<class T> using rpriority_queue = priority_queue<T, vector<T>, greater<T>>;
const int MOD=1000000007;
const int MOD2=998244353;
const int INF=1<<30;
const ll INF2=1LL<<60;
void scan(int& a){scanf("%d",&a);}
void scan(long long& a){scanf("%lld",&a);}
template<class T,class L>void scan(pair<T, L>& p){scan(p.first);scan(p.second);}
template<class T,class U,class V>void scan(tuple<T,U,V>& p){scan(get<0>(p));scan(get<1>(p));scan(get<2>(p));}
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i);}
template<class T> void scan(T& a){cin>>a;}
template<class T> void scan(vector<T>& vec){for(auto&& it:vec)scan(it);}
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){scan(head);in(tail...);}
void print(const int& a){printf("%d",a);}
void print(const long long& a){printf("%lld",a);}
void print(const double& a){printf("%.15lf",a);}
template<class T,class L>void print(const pair<T, L>& p){print(p.first);putchar(' ');print(p.second);}
template<class T> void print(const T& a){cout<<a;}
template<class T> void print(const vector<T>& vec){if(vec.empty())return;print(vec[0]);for(auto it=vec.begin();++it!= vec.end();){putchar(' ');print(*it);}}
void out(){putchar('\n');}
template<class T> void out(const T& t){print(t);putchar('\n');}
template <class Head, class... Tail> void out(const Head& head,const Tail&... tail){print(head);putchar(' ');out(tail...);}
template<class T> void dprint(const T& a){cerr<<a;}
template<class T> void dprint(const vector<T>& vec){if(vec.empty())return;cerr<<vec[0];for(auto it=vec.begin();++it!= vec.end();){cerr<<" "<<*it;}}
void debug(){cerr<<endl;}
template<class T> void debug(const T& t){dprint(t);cerr<<endl;}
template <class Head, class... Tail> void debug(const Head& head, const Tail&... tail){dprint(head);cerr<<" ";debug(tail...);}
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
ll modinv(ll a, ll m) {ll b = m, u = 1, v = 0;while (b) {ll t = a / b;a -= t * b; swap(a, b);u -= t * v; swap(u, v);}u %= m;if (u < 0) u += m;return u;}
ll updivide(ll a,ll b){return (a+b-1)/b;}
int msb(ll v){return 63-__builtin_clzll(v);}
template<class T> void chmax(T &a,const T b){if(b>a)a=b;}
template<class T> void chmin(T &a,const T b){if(b<a)a=b;}

int main(){
    INT(n,m);
    vector<vector<int>> t(m);
    rep(i,n){
        INT(x);
        t[--x].push_back(i);
    }
    vector<int> dp(1<<m,0);
    rep(i,1<<m){
        int l=0,r;
        rep(j,m)if(i>>j&1)l+=t[j].size();
        rep(j,m){
            if(~i>>j&1){
                r=l+t[j].size();
                int plus=lower_bound(all(t[j]),r)-lower_bound(all(t[j]),l);
                chmax(dp[i^(1<<j)],dp[i]+plus);
            }
        }
    }
    out(n-dp.back());
}
accuracy: 1
time_ms: 790
memory_kb: 7652
final_rank: 10

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
 
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, int> pii;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
 
 
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
 
#define MOD 1000000007
 
template<class T1, class T2> inline bool chmax(T1 &a, T2 b) {if (a < b) {a = b; return true;} return false;}
template<class T1, class T2> inline bool chmin(T1 &a, T2 b) {if (a > b) {a = b; return true;} return false;}
const double EPS = 1e-8, PI = acos(-1);
const double pi = 3.141592653589793238462643383279;
//ここから編集    
typedef string::const_iterator State;
ll GCD(ll a, ll b){
  return (b==0)?a:GCD(b, a%b);
}
ll LCM(ll a, ll b){
  return a/GCD(a, b) * b;
}
template< int mod >
struct ModInt {
  int x;
 
  ModInt() : x(0) {}
 
  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
 
  ModInt &operator+=(const ModInt &p) {
    if((x += p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator-=(const ModInt &p) {
    if((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator*=(const ModInt &p) {
    x = (int) (1LL * x * p.x % mod);
    return *this;
  }
 
  ModInt &operator/=(const ModInt &p) {
    *this *= p.inverse();
    return *this;
  }
 
  ModInt operator-() const { return ModInt(-x); }
 
  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
 
  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
 
  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
 
  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
 
  bool operator==(const ModInt &p) const { return x == p.x; }
 
  bool operator!=(const ModInt &p) const { return x != p.x; }
 
  ModInt inverse() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while(b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }
 
  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while(n > 0) {
      if(n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
 
  friend ostream &operator<<(ostream &os, const ModInt &p) {
    return os << p.x;
  }
 
  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt< mod >(t);
    return (is);
  }
 
  static int get_mod() { return mod; }
};
 
using modint = ModInt< 1000000007 >;
template< typename T >
struct Combination {
  vector< T > _fact, _rfact, _inv;
 
  Combination(int sz) : _fact(sz + 1), _rfact(sz + 1), _inv(sz + 1) {
    _fact[0] = _rfact[sz] = _inv[0] = 1;
    for(int i = 1; i <= sz; i++) _fact[i] = _fact[i - 1] * i;
    _rfact[sz] /= _fact[sz];
    for(int i = sz - 1; i >= 0; i--) _rfact[i] = _rfact[i + 1] * (i + 1);
    for(int i = 1; i <= sz; i++) _inv[i] = _rfact[i] * _fact[i - 1];
  }
 
  inline T fact(int k) const { return _fact[k]; }
 
  inline T rfact(int k) const { return _rfact[k]; }
 
  inline T inv(int k) const { return _inv[k]; }
 
  T P(int n, int r) const {
    if(r < 0 || n < r) return 0;
    return fact(n) * rfact(n - r);
  }
 
  T C(int p, int q) const {
    if(q < 0 || p < q) return 0;
    return fact(p) * rfact(q) * rfact(p - q);
  }
 
  T H(int n, int r) const {
    if(n < 0 || r < 0) return (0);
    return r == 0 ? 1 : C(n + r - 1, r);
  }
};
 
ll modpow(ll x, ll n, ll mod) {
  ll res = 1;
  while(n) {
    if(n&1) res = (res * x) % mod;
    x = (x * x) % mod;
    n >>= 1;
  }
  return res;
} 
inline long long mod(long long a, long long m) {
    return (a % m + m) % m;
}
template<typename T> 
struct BIT{
  int N;
  std::vector<T> node;

  BIT(int n){
    N = n;
    node.resize(N+10);
  }

  /* a: 1-indexed */
  void add(int a, T x){
    for(int i=a; i<(int)node.size(); i += i & -i) node[i] += x;
  }

  /* [1, a] */
  T sum(int a){
    T res = 0;
    for(int x=a; x>0; x -= x & -x) res += node[x];
    return res;
  }

  /* [l, r] */
  T rangesum(int l, int r){
    return sum(r) - sum(l-1);
  }

  /* 
    a1+a2+...+aw >= valとなるような最小のwを返す
    @verify https://codeforces.com/contest/992/problem/E
  */
  int lower_bound(T val) {
    if(val < 0) return 0;

    int res = 0;
    int n = 1; 
    while (n < N) n *= 2;

    T tv=0;
    for (int k = n; k > 0; k /= 2) {
      if(res + k < N && node[res + k] < val){
        val -= node[res+k];
        res += k;
      }
    }
    return res+1; 
  }
};
struct UnionFind{
  std::vector<int> par;
  std::vector<int> siz;

  UnionFind(int sz_): par(sz_), siz(sz_) {
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  void init(int sz_){
    par.resize(sz_);
    siz.resize(sz_);
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  int root(int x){
    if(x == par[x]) return x;
    return par[x] = root(par[x]);
  }

  bool merge(int x, int y){
    x = root(x), y = root(y);
    if(x == y) return false;
    if(siz[x] < siz[y]) std::swap(x, y);
    siz[x] += siz[y];
    par[y] = x;
    return true;
  }

  bool issame(int x, int y){
    return root(x) == root(y);
  }

  int size(int x){
    return siz[root(x)];
  }
};
struct RollingHash{

    using ull = unsigned long long;
    const ull mod = (1ULL << 61) - 1;
    const ull MASK30 = (1ULL << 30) - 1;
    const ull MASK31 = (1ULL << 31) - 1;

    const ull MASK61 = mod;

    ull base;
    int n;
    vector<ull> hash, pow;

    RollingHash(const string &s)
    {
        random_device rnd;
        mt19937_64 mt(rnd());
        base = calc_mod(mt()) % 100000 + 1000;
        
        n = (int)s.size();
        hash.assign(n+1, 0);
        pow.assign(n+1, 1);
        
        for(int i=0; i<n; i++){
            hash[i+1] = calc_mod(mul(hash[i], base) + s[i]);
            pow[i+1] = calc_mod(mul(pow[i], base));
        }
    }

    ull calc_mod(ull x){
        ull xu = x >> 61;
        ull xd = x & MASK61;
        ull res = xu + xd;
        if(res >= mod) res -= mod;
        return res;
    }

    ull mul(ull a, ull b){
        ull au = a >> 31;
        ull ad = a & MASK31;
        ull bu = b >> 31;
        ull bd = b & MASK31;
        ull mid = ad * bu + au * bd;
        ull midu = mid >> 30;
        ull midd = mid & MASK30;
        return calc_mod(au * bu * 2 + midu + (midd << 31) + ad * bd);
    }

    //[l,r)のハッシュ値
    inline ull get(int l, int r){
        ull res = calc_mod(hash[r] + mod*3-mul(hash[l], pow[r-l]));
        return res;
    }
    //string tのハッシュ値
    inline ull get(string t){
        ull res = 0;
        for(int i=0; i<t.size(); i++){
            res = calc_mod(mul(res, base)+t[i]);
        }
        return res;
    }
    //string s中のtの数をカウント
    inline int count(string t) {
        if(t.size() > n) return 0;
        auto hs = get(t);
        int res = 0;
        for(int i=0; i<n-t.size()+1; i++){
            if(get(i, i+t.size()) == hs) res++; 
        }
        return res;
    }

    /* 
        concat 
        @verify https://codeforces.com/problemset/problem/514/C
    */
    inline ull concat(ull h1, ull h2, int h2len){
      return calc_mod(h2 + mul(h1, pow[h2len]));
    }

    // LCPを求める S[a:] T[b:]
    inline int LCP(int a, int b){
        int len = min((int)hash.size()-a, (int)hash.size()-b);
        
        int lb = -1, ub = len;
        while(ub-lb>1){
            int mid = (lb+ub)/2;

            if(get(a, a+mid) == get(b, b+mid)) lb = mid;
            else ub = mid;
        }
        return lb;
    }
};
int dp[(1<<20)];
int main() {  
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(12);

  int n, m; cin >> n >> m;
  REP(i,(1<<m)) dp[i] = 1e9;
  dp[0] = 0;
  vector<int> a(n);
  REP(i,n) cin >> a[i];
  vector<vector<int>> cums(m, vector<int>(n+1));
  REP(i,n) {
    a[i]--;
    cums[a[i]][i+1]++;
    for(int j=0; j<m; j++) {
      cums[j][i+1] += cums[j][i];
    }
  }
  REP(bit,(1<<m)) {
    int sum = 0;
    REP(i,m) if(bit >> i & 1) sum += cums[i][n];
    REP(i,m) {
      if(bit >> i & 1) continue;
      int t = cums[i][n];
      dp[bit | (1 << i)] = min(dp[bit | (1 << i)], dp[bit] + t - (cums[i][sum+t]-cums[i][sum]));
    }
  }
  cout << dp[(1<<m)-1] << endl;
  return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 15900
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, N) for (int i = 0; i < N; i++)
int main()
{
  int INF = 1000100100;
  int N, M;
  cin >> N >> M;
  int A[N];
  rep(i, N)
  {
    cin >> A[i];
    A[i]--;
  }
  int ac[M][N]={};
  ac[A[0]][0]++;
  
  for (int j = 1; j < N; j++)
  {
    rep(i, M)
    {
      ac[i][j] = ac[i][j - 1];
      if (A[j] == i)
        ac[i][j]++;
    }
  }
/*  rep(i, M)
  {
    rep(j, N) { cout << ac[i][j] << " | "; }
    cout << endl;
  } */
  int dp[1 << M];
  rep(i, 1 << M) dp[i] = INF;
  dp[0] = 0;
  int cnt[M] = {};
  rep(i, N)
  {
    cnt[A[i]]++;
  }
//  rep(i, M) cout << cnt[i] << " |cnt| ";
 // cout << endl;

  rep(s, 1 << M)
  {
//    cout << " s " << s << endl;
    int done = 0;
    rep(i, M)
    {
      if (s & (1 << i))
      {
        done += cnt[i];
      }
    }

    rep(i, M)
    {
   //   cout << " i " << i << " done " << done << endl;

      if(s & (1 << i))
        continue; // iがsに含まれているならスキップ
      int cost;
      if(done == 0) {
        cost = cnt[i] - ac[i][cnt[i] -1];
    //    cout << " cost " << cost << " cnt " << cnt[i] << " - " << ac[i][cnt[i] -1] << endl;
      }
      else {
        cost = cnt[i] - (ac[i][cnt[i] -1 + done] - ac[i][done -1]);
      }
   //   cout << i << " i cost " << cost << " dp[s|1<<i] " << dp[s|1<<i] << " dp[s] " << dp[s] << endl;

      dp[s|1<<i] = min(dp[s|1<<i], dp[s] + cost);

   //   rep(i,1<<M) cout << bitset<4>(i)<< ":" << dp[i] << " |dp| "; cout << endl;
    }
  }
  cout << dp[(1<<M)-1] << endl;
}
accuracy: 1
time_ms: 110
memory_kb: 15388
final_rank: 2

code_snippet: #include <bits/stdc++.h>          
using namespace std;
using ll = long long;
using ld = long double;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define repp(i, st, en) for (ll i = (ll)st; i < (ll)(en); i++)
#define repm(i, st, en) for (ll i = (ll)st; i >= (ll)(en); i--)
#define all(v) v.begin(), v.end()
void chmax(ll &x, ll y) {x = max(x,y);}
void chmin(ll &x, ll y) {x = min(x,y);}
void Yes() {cout << "Yes" << endl; exit(0);}
void No() {cout << "No" << endl; exit(0);}
template<class in_Cout> void Cout(in_Cout x) {cout << x << endl; exit(0);}
template<class in_vec_cout>
void vec_cout(vector<in_vec_cout> vec) {
    for (in_vec_cout res : vec) {cout << res << " ";}
    cout << endl;
}

const ll inf = 1e18;
const ll mod = 1e9 + 7;

int main() {
    ll N, M; cin >> N >> M;
    vector<ll> a(N);
    rep(i,N) cin >> a[i];
    rep(i,N) a[i]--;
    vector<ll> cnt(M);
    rep(i,N) cnt[a[i]]++;
    vector<vector<ll>> S(M,vector<ll>(N));
    rep(i,N) S[a[i]][i] = 1;
    rep(i,M) repp(j,1,N) S[i][j] += S[i][j-1];

    vector<ll> dp(1<<M,inf);
    dp[0] = 0;
    rep(bit,1<<M) {
        ll l = 0;
        rep(i,M) if ((bit>>i)&1) l += cnt[i];
        rep(i,M) {
            if ((bit>>i)&1) continue;
            ll nbit = bit | (1<<i);
            ll L = 0, R = 0;
            if (l+cnt[i]-1>=0) R = S[i][l+cnt[i]-1];
            if (l-1>=0) L = S[i][l-1];
            ll cost = cnt[i] - (R-L);
            chmin(dp[nbit],dp[bit]+cost);
        }
    }
    ll X = (1<<M) - 1;
    ll ans = dp[X];
    Cout(ans);
}
accuracy: 1
time_ms: 110
memory_kb: 27680
final_rank: 11

code_snippet: #include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, x) for(ll i = 0; i < x; i++)
#define rep2(i, x) for(ll i = 1; i <= x; i++)
#define all(a) (a).begin(),(a).end()
#define puts(x) cout << x << "\n";
using ll = int;
using ld = long double;
using namespace std;

//入力
ll n, m;
vector<ll> syu(100005), ko(21);
vector<vector<ll>> rui(21, vector<ll>(100005));

// メモ再帰
ll dp[1 << 21];
ll rec(ll bit) {
	// すでに探索済みだったらリターン
	if (dp[bit] != -1) return dp[bit];

	// 答えを格納する変数
	int res = 1000000;
	rep (v, m) {
		//集合bitにvが含まれるか
		if ((bit & (1 << v)) != 0) {
			// bit の v を除いたもの
			ll prev_bit = bit & ~(1 << v);

			ll start = 0;
			rep(i, m) {
				if ((prev_bit & (1 << i)) != 0) { start += ko[i]; }
			}

			ll ans = rec(prev_bit);
			ll sum = rui[v][start + ko[v] - 1];
			if (start != 0) { sum -= rui[v][start - 1]; }
			ans += ko[v] - sum;

			// 再帰的に探索
			if (res > ans) {
				res = ans;
			}
		}
	}
	return dp[bit] = res; // メモしながらリターン
}

signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//cout << fixed << setprecision(15);

	//input
	cin >> n >> m;
	rep(i, n) { cin >> syu[i]; syu[i]--; rui[syu[i]][i]++; ko[syu[i]]++; }
	rep(i, n) {
		if (i == 0) { continue; }
		rep(j, m) {
			rui[j][i] += rui[j][i - 1];
		}
	}
	// テーブルを全部 -1 にしておく (-1 でなかったところは探索済)
	for (int bit = 0; bit < (1 << m); ++bit) dp[bit] = -1;
	dp[0] = 0;
	cout << rec((1 << m) - 1) << endl;
	return 0;
}
accuracy: 1
time_ms: 270
memory_kb: 15420
final_rank: 8