Problem:
Patience
As the proverb says,
"Patience is bitter, but its fruit is sweet."
Writing programs within the limited time may impose 
some patience on you, but you enjoy it and win the contest, we hope.
The word "patience" has the meaning of perseverance, 
but it has another meaning in card games.
Card games for one player are called "patience" in the UK
and "solitaire" in the US.
Let's play a patience in this problem.
In this card game, you use only twenty cards whose 
face values are positive and less than or equal to 5 (Ace's value
is 1 as usual).
Just four cards are available for each face value.
At the beginning, the twenty cards are laid
in five rows by four columns (See Figure 1).
All the cards are dealt face up.
An example of the initial layout is shown in Figure 2.
Figure 1: Initial layout
Figure 2: Example of the initial layout
The purpose of the game is to remove as many cards as possible
by repeatedly removing a pair of neighboring cards 
of the same face value.
Let us call such a pair a
matching pair
.
The phrase "a pair of neighboring cards" means a pair of cards which are
adjacent to each other.
For example, in Figure 1,
C
6
is adjacent to any of
the following eight cards:
C
1
,
C
2
,
C
3
,
C
5
,
C
7
,
C
9
,
C
10
and
C
11
.
In contrast,
C
3
is adjacent to only the following three cards:
C
2
,
C
6
and
C
7
.
Every time you remove a pair, you must rearrange the remaining cards 
as compact as possible.
To put it concretely, each remaining card
C
i
must be examined in turn
in its subscript order to be shifted to the uppermost-leftmost
space.
How to play:
Search a matching pair.
When you find more than one pair, choose one.
In Figure 3, you decided to remove the pair of
C
6
and
C
9
.
Remove the pair. (See Figure 4)
Shift the remaining cards to the uppermost-leftmost space
(See Figure 5, 6).
Repeat the above procedure until you cannot remove any pair.
Figure 3: A matching pair found
Figure 4: Remove the matching pair
Figure 5: Shift the remaining cards
Figure 6: Rearranged layout
If you can remove all the twenty cards, you win the game 
and your penalty is 0.
If you leave some cards,
you lose the game and 
your penalty is the number of the remaining cards.
Whenever you find multiple matching pairs,
you must choose one pair out of them 
as in the step 2 of the above procedure.
The result of the game depends on these choices.
Your job is to write a program which answers the minimal penalty
for each initial layout.
Input
The input consists of multiple card layouts.
The input is given in the following format.
N
Layout
0
Layout
1
...
Layout
N
-1
N
is the number of card layouts.
Each card layout gives the initial state of a game.
A card layout is given in the following format.
C
0
C
1
C
2
C
3
C
4
C
5
C
6
C
7
C
8
C
9
C
10
C
11
C
12
C
13
C
14
C
15
C
16
C
17
C
18
C
19
C
i
(0 <=
i
<= 19) is an integer 
from 1 to 5 which represents the face value of the card.
Output
For every initial card layout, the minimal penalty should be output,
each in a separate l
...(truncated)

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define rrep(i,a,b) for(int i=a;i>=b;--i)
#define GRPS int T;scanf("%d",&T);rep(C,1,T)
#define GRP int T;cin>>T;rep(C,1,T)
#define ETR putchar('\n')
#define IN1(a) scanf("%d",&a)
#define IN2(a,b) scanf("%d %d",&a,&b)
#define IN3(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define elif else if
#define mem(arr,val) memset(arr,val,sizeof(arr))
#define FAST ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

vector<int> c;
int res, tmp;
int dis[] = {1, 3, 4, 5};

void dfs(vector<int> &a) {
	int sz = a.size();
	if (sz == 0) {
		res = 0;
		return;
	}
	bool fnd = false;
	rep(i, 0, sz - 1) {
		for (int d : dis) {
			if (i + d >= 0 && i + d < sz && a[i] == a[i + d]) {
				if (i % 4 == 3 && (d == 1 || d == 5)) {
					continue;
				}
				if (i % 4 == 0 && d == 3) {
					continue;
				}
				vector<int> t(a);
				t.erase(t.begin() + i);
				t.erase(t.begin() + i + d - 1);
				fnd = true;
				/*
				int cnt = 0;
				for (int aa : t) {
					cout << aa << ' ';
					cnt++;
					if (cnt == 4) {
						cout << endl;
						cnt = 0;
					}
				}
				cout << endl << endl;;
				*/
				dfs(t);
			}
		}
	}
	if (!fnd) {
		res = min(res, sz);
	}
}

int main() {

	//freopen("patient.out", "w", stdout);

	FAST;
	GRP{
		c.clear();
		rep(i, 0, 19) {
			cin >> tmp;
			c.push_back(tmp);
		}
		/*
		int cnt = 0;
		for (int m : c) {
			cout << m << ' ';
			cnt++;
			if (cnt == 4) {
				cout << endl;
				cnt = 0;
			}
		}
		cout << endl;
		*/
		res = 22;
		dfs(c);
		cout << res << endl;
	}

	return 0;
}

/**
*　　┏┓　　　┏┓+ +
*　┏┛┻━━━┛┻┓ + +
*　┃　　　　　　　┃
*　┃　　　━　　　┃ ++ + + +
*  ████━████+
*  ◥██◤　◥██◤ +
*　┃　　　┻　　　┃
*　┃　　　　　　　┃ + +
*　┗━┓　　　┏━┛
*　　　┃　　　┃ + + + +
*　　　┃　　　┃ + + + + + +
*　　　┃　 　 ┗━━━┓ 　
*　　　┃ 　　　　　　 ┣┓
*　　  ┃ 　　　　　 　┏┛
*　    ┗┓┓┏━┳┓┏┛ + + + +
*　　　　┃┫┫　┃┫┫
*　　　　┗┻┛　┗┻┛+ + + +
*/
accuracy: 1
time_ms: 10
memory_kb: 3144
final_rank: 8

code_snippet: #include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
#define rep(i, m, n) for (ll i = (ll)m; i < (ll)n; i++)
#define drep(i, m, n) for (ll i = m - 1; i >= n; i--)
#define Endl endl
#define all(a) a.begin(), a.end()
#define pr(i, j) make_pair(i, j)
#define isin(x, l, r) (l <= x && x < r)
#define chmin(a, b) a = min(a, b)
#define chmax(a, b) a = max(a, b)
#define srt(ar) sort(ar.begin(), ar.end())
#define rev(ar) reverse(ar.begin(), ar.end())
#define jge(f, s, t) cout << (f ? s : t) << endl
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#define printar(ar)             \
    do                          \
    {                           \
        for (auto dbg : ar)     \
        {                       \
            cout << dbg << " "; \
        }                       \
        cout << endl;           \
    } while (0)
const ll inf = 1e18;
const ld pi = 3.14159265358979;
const ld eps = 1e-9;
template <class T, ll n, ll idx = 0>
auto make_vec(const ll (&d)[n], const T &init) noexcept
{
    if constexpr (idx < n)
        return std::vector(d[idx], make_vec<T, n, idx + 1>(d, init));
    else
        return init;
}

template <class T, ll n>
auto make_vec(const ll (&d)[n]) noexcept
{
    return make_vec(d, T{});
}
//////////////// 以下を貼る ////////////////
template <class T>
size_t HashCombine(const size_t seed, const T &v)
{
    return seed ^ (std::hash<T>()(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
}
/* pair用 */
template <class T, class S>
struct std::hash<std::pair<T, S>>
{
    size_t operator()(const std::pair<T, S> &keyval) const noexcept
    {
        return HashCombine(std::hash<T>()(keyval.first), keyval.second);
    }
};
////////////////////////////////////////////
ll f(vector<vector<ll>> c)
{
    ll ret = 0;
    rep(i, 0, 5)
    {
        rep(j, 0, 4)
        {
            if (c[i][j] != -1)
            {
                ret++;
            }
        }
    }
    vector<ll> dx = {0, 1, 1, 1};
    vector<ll> dy = {1, -1, 0, 1};
    rep(i, 0, 5)
    {
        rep(j, 0, 4)
        {
            if (c[i][j] == -1)
            {
                continue;
            }
            rep(k, 0, 4)
            {
                ll nx = i + dx[k];
                ll ny = j + dy[k];
                if (isin(nx, 0, 5) && isin(ny, 0, 4))
                {
                    if (c[i][j] == c[nx][ny])
                    {
                        vector<ll> ar;
                        rep(a, 0, 5)
                        {
                            rep(b, 0, 4)
                            {
                                if (a == i && b == j)
                                {
                                    continue;
                                }
                                if (a == nx && b == ny)
                                {
                                    continue;
                                }
                                if (c[a][b] == -1)
                                {
                                    continue;
                                }
                                ar.push_back(c[a][b]);
                            }
                        }
                        vector<vector<ll>> nxt(5, vector<ll>(4, -1));
                        rep(a, 0, ar.size())
                        {
                            nxt[a / 4][a % 4] = ar[a];
                        }
                        chmin(ret, f(nxt));
                    }
                }
            }
        }
    }
    return ret;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll n;
    cin >> n;
    while (n--)
    {
        vector<vector<ll>> c(5, vector<ll>(4));
        rep(i, 0, 5)
        {
            rep(j, 0, 4)
            {
                cin >> c[i][j];
            }
        }
        cout << f(c) << endl;
    }
}
accuracy: 1
time_ms: 130
memory_kb: 3456
final_rank: 20

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


using namespace std;
//make -f ../makefile SRC=
/*
*/


//------------------------------------------------------------------------------
bool DEBUG = false;
const int INF = 2147483647;

const int M = 5;
const int N = 4;
const int K = 20;
typedef vector<int> State;
typedef vector<State> States;

/*
typedef pair<int,int> PA;
const int A = 8;
static vector<PA> actions = {{0,-1}, {0,1}, {-1,0}, {1,0}, {-1,1}, {-1,-1}, {1,-1}, {1,1}};
*/
//------------------------------------------------------------------------------
void debug_state(const State& s1)
{
    int N1 = s1.size();
    bool finished = false;
    for (int m=0; m<M; ++m)
    {
        if (finished) break;
        for (int n=0; n<N; ++n)
        {
            int v = m*N + n;
            if (v >= N1) { finished = true; break; }
            printf("%d ",s1[v]);
        }
        printf("\n");
    }
    printf("\n");
}

State shift(const State& s1, int v1, int v2)
{
    int N1 = s1.size();
    State s2(N1-2);
    int index = 0;
    for (int v=0; v<N1; ++v)
        if (v != v1 && v != v2)
            s2[index++] = s1[v];
    return s2;
}

States successors(const State& s1)
{
    States states;
    int N1 = s1.size();
    for (int v1=0; v1<N1-1; ++v1)
        for (int v2=v1+1; v2<N1; ++v2)
            if (s1[v1] == s1[v2] && abs(v1/N-v2/N) <= 1 && abs(v1%N-v2%N) <= 1)
                states.push_back( shift(s1, v1, v2) );

    return states;
}
//------------------------------------------------------------------------------
int bfs(const State& src)
{
    if (DEBUG)
    {
        for (State w: successors(src)) debug_state(w);
    }
    queue<State> Q;
    Q.push(src);
    int res = 20;
    //--------------------------------------------------------------------------
    // search:
    while (!Q.empty())
    {
        State v = Q.front(); Q.pop();
        if (v.empty()) return 0;
        res = min(res, int(v.size()));

        for (State w: successors(v)) Q.push(w);
    }
    return res;
}

//------------------------------------------------------------------------------
int main()
{
    //test(); return 0;
    //DEBUG = true;
    //--------------------------------------------------------------------------
    int T, v, num;
    num = scanf("%d ", &T);
    while (T--)
    {
        State src(K);
        for (int k=0; k<K; ++k)
        {
            num = scanf("%d ", &v);
            src[k] = v;
        }
        if (DEBUG) debug_state(src);
        int res = bfs(src);
        printf("%d\n", res);
    }
    //--------------------------------------------------------------------------
    return 0;
}
//------------------------------------------------------------------------------
accuracy: 1
time_ms: 40
memory_kb: 5468
final_rank: 18

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

int was[1 << 20], c[20];

int rec(int mask) {
    if (was[mask] != -1) return was[mask];
    if (mask == 0) return was[mask] = 0;
    vector<int> now;
    for (int i = 0; i < 20; ++i) {
        if (mask >> i & 1) now.push_back(i);
    }
    int& ret = was[mask];
    ret = now.size();
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 4; ++j) {
            for (int dx = -1; dx <= 1; ++dx) {
                for (int dy = -1; dy <= 1; ++dy) {
                    int x = i + dx, y = j + dy;
                    if (x < 0 || y < 0 || y >= 4 || x >= 5) continue;
                    int u = i * 4 + j, v = x * 4 + y;
                    if (u == v) continue;
                    if (u < now.size() && v < now.size() && c[now[u]] == c[now[v]]) {
                        ret = min(ret, rec(mask ^ (1 << now[u]) ^ (1 << now[v])));
                    }
                }
            }
        }
    }
    return ret;
}

int main() {
    cin.tie(0)->sync_with_stdio(0);

    int tests;
    cin >> tests;
    while (tests--) {
        for (int i = 0; i < 20; ++i) cin >> c[i];
        fill(was, was + (1 << 20), -1);
        cout << rec((1 << 20) - 1) << '\n';
    }
}
accuracy: 1
time_ms: 10
memory_kb: 7116
final_rank: 19

code_snippet: #include<stdio.h>
#include<iostream>
#include<string.h>

int table[20];

int dx[4] = { 1,-1,0,1 };
int dy[4] = { 0,1,1,1, };

int checkRange(int row, int col)
{
	if (row >= 0 && row < 5 && col >= 0 && col < 4)
		return 1;
	return 0;
}

void move(int* table, int n)
{
	int* p = table;
	int* q = 0;
	while (p < table + n)
	{
		if (*p == 0)
		{
			if (q == 0)
				q = p;
		}
		else
		{
			if (q != 0)
			{
				*q = *p;
				*p = 0;
				q++;
			}
		}
		p++;
	}
}



int slove(int* t)
{
	int tmp[20];
	int x, y, col, row;
	int ret;
	int min_val = 20;
	for (int i = 0; i < 20; i++)
	{
		if (t[i] == 0)
			break;

		col = i % 4;
		row = i / 4;

		for (int k = 0; k < 4; k++)
		{
			x = col + dx[k];
			y = row + dy[k];
			if (checkRange(y, x) &&  t[i] == t[y * 4 + x])
			{
				memcpy(tmp, t, sizeof(tmp));
				tmp[i] =  tmp[y * 4 + x] =  0;
				move(tmp, 20);
				ret = slove(tmp);
				if (min_val > ret)
					min_val = ret;
			}
		}
	}

	if (min_val == 20)
	{
		min_val = 0;
		for (int i = 0; i < 20; i++)
		{
			if (t[i] != 0)
				min_val++;
			else
				break;
		}
	}
	return min_val;
}

int main()
{
	int n;
	std::cin >> n;
	int ret;
	for (int i = 0; i < n; i++)
	{
		for (int row = 0; row < 5; row++)
		{
			for (int col = 0; col < 4; col++)
			{
				std::cin >> table[row * 4 + col];
			}
		}
		ret = slove(table);
		std::cout << ret << std::endl;
	}



	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 2996
final_rank: 7

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;
int diff[] = {1, 3, 4, 5};

int solve(vector<int> a){
    int res = 0;
    for(int i=0; i<(int)a.size(); i++){
        for(int d=0; d<4; d++){
            if(i%4==0 and diff[d]==3) continue;
            if(i%4==3 and (diff[d]==1 or diff[d]==5)) continue;
            if(i+diff[d] < (int)a.size() and a[i] == a[i+diff[d]]){
                auto b = a;
                b.erase(b.begin() +i+diff[d]);
                b.erase(b.begin() +i);
                res = max(res, solve(b) +2);
            }
        }     
    }
    return res;
}

int main(){
    int nt;
    cin >> nt;
    for(int rep=0; rep<nt; rep++){
        vector<int> a(20);
        for(int i=0; i<20; i++){
            cin >> a[i];
        }
        cout << 20 -solve(a) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3080
final_rank: 14

code_snippet: #include<bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef pair<string,int>P;
int dy[]={-1,-1,-1,0,0,1,1,1};
int dx[]={-1,0,1,-1,1,-1,0,1};
int n,pp;
int h=5,w=4;
string a;
map<string,int>used;
int bfs(){
  int ans=20;
  queue<P>q;
  used[a]=1;
  q.push(P(a,1));
  while(!q.empty()){
    P p=q.front();q.pop();
    string now=p.first;
    int cost=p.second;
    int b[5][4],t=0;
    r(i,5)r(j,4)b[i][j]=(int)now[t++];
    r(i,5)r(j,4){
      r(k,8){
	int y=i+dy[k];
	int x=j+dx[k];
	if(y<0||x<0||x>=w||y>=h)continue;
	if(b[i][j]==b[y][x]&&b[i][j]){
	  int c[5][4];
	  r(i1,5)r(j1,4)c[i1][j1]=b[i1][j1];
	  c[i][j]=c[y][x]=0;
	  string next;
	  r(i1,5)r(j1,4)if(c[i1][j1])next+=(char)c[i1][j1];
	  ans=min(ans,(int)next.size());
	  while(next.size()<20)next+=(char)0;
	  if(used[next])continue;
	  used[next]=1;
	  q.push(P(next,1));
	}
      }
    }
  }
  return ans;
}
int main(){
  cin>>n;
  while(n--){
    a="";
    used.clear();
    r(i,5)r(j,4){
      cin>>pp;
      a+=pp;
    }
    cout<<bfs()<<endl;
  }
}
accuracy: 1
time_ms: 10
memory_kb: 3256
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int dx[8]={-1,-1,-1,0,0,1,1,1},dy[8]={-1,0,1,-1,1,-1,0,1};
bool check(int n,int m,int x,int y){return x>=0&&x<n&&y>=0&&y<m;}
 
bool dp[1<<20];
int main() {
  int T,n=5,m=4;
  cin >> T;
  while(T--) {
    int d[20];
    for(int i=0; i<20; i++) cin >> d[i];
    memset(dp,0,sizeof(dp));
    dp[(1<<20)-1]=1;
    int ans=1<<29;
    for(int t=(1<<20)-1; t>=0; t--) {
      if(dp[t]) ans=min(ans,__builtin_popcount(t));
      else continue;
      P a[n][m];
      memset(a,-1,sizeof(a));
      for(int i=0,k=0; i<20; i++) {
        if(t&(1<<i)) {
          a[k/m][k%m]=P(d[i],i);
          k++;
        }
      }
      for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
          if(a[i][j].first==-1) break;
          for(int k=0; k<8; k++) {
            int x=i+dx[k],y=j+dy[k];
            if(!check(n,m,x,y)) continue;
            if(a[i][j].first==a[x][y].first) {
              dp[t^(1<<a[i][j].second)^(1<<a[x][y].second)]|=dp[t];
            }
          }
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4064
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int dx[8]={-1,-1,-1,0,0,1,1,1},dy[8]={-1,0,1,-1,1,-1,0,1};
bool check(int n,int m,int x,int y){return x>=0&&x<n&&y>=0&&y<m;}

bool dp[1<<20];
int main() {
  int T,n=5,m=4;
  cin >> T;
  while(T--) {
    int d[20];
    for(int i=0; i<20; i++) cin >> d[i];
    memset(dp,0,sizeof(dp));
    dp[(1<<20)-1]=1;
    int ans=1<<29;
    for(int t=(1<<20)-1; t>=0; t--) {
      if(dp[t]) ans=min(ans,__builtin_popcount(t));
      else continue;
      P a[n][m];
      memset(a,-1,sizeof(a));
      for(int i=0,k=0; i<20; i++) {
	if(t&(1<<i)) {
	  a[k/m][k%m]=P(d[i],i);
	  k++;
	}
      }
      for(int i=0; i<n; i++) {
	for(int j=0; j<m; j++) {
	  if(a[i][j].first==-1) break;
	  for(int k=0; k<8; k++) {
	    int x=i+dx[k],y=j+dy[k];
	    if(!check(n,m,x,y)) continue;
	    if(a[i][j].first==a[x][y].first) {
	      dp[t^(1<<a[i][j].second)^(1<<a[x][y].second)]|=dp[t];
	    }
	  }
	}
      }
    }
    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3964
final_rank: 11

code_snippet: #include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<int,pii> pip;
typedef vector<pip>vip;
const double PI=acos(-1);
const double EPS=1e-5;
const int inf=1e8;
int out;
int dx[]={0,1,1,1};
int dy[]={1,-1,0,1};
void dfs(vi &in){
	rep(i,in.size()){
		int x=i/4,y=i%4;
		rep(j,4){
			int nx=x+dx[j],ny=y+dy[j];
			if(nx<0||ny<0||nx>=5||ny>=4)continue;
//			cout<<x<<" "<<y<<" "<<nx<<" "<<ny<<endl;
			int t=nx*4+ny;
			if(t>=in.size())continue;
			if(in[i]==in[t]){
				vi tm=in;
				tm.erase(tm.begin()+t);
				tm.erase(tm.begin()+i);
				out=min(out,(int)tm.size());
				dfs(tm);
			}
		}
	}
}
int main(){
	int q;
	cin>>q;
	while(q--){
		vi in(20);
		rep(i,20)cin>>in[i];
		out=20;
		dfs(in);
		cout<<out<<endl;
	}
}
accuracy: 1
time_ms: 20
memory_kb: 2924
final_rank: 10

code_snippet: #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int n, a[20], dp[1 << 20]; bool vis[1 << 20];
int rec(int used) {
	if (vis[used]) return dp[used];
	int r = 0;
	int b[20] = { 0 }, c[20] = { 0 };
	for (int i = 0; i < 20; i++) {
		if (used & (1 << i)) {
			b[r] = a[i], c[r++] = i;
		}
	}
	int ret = r;
	for (int i = 0; i < r; i++) {
		int ty = i >> 2, tx = i & 3;
		for (int j = -1; j <= 1; j++) {
			for (int k = -1; k <= 1; k++) {
				if (!j && !k) continue;
				int ry = ty + j, rx = tx + k, t = 4 * ry + rx;
				if (0 <= ry && ry < 5 && 0 <= rx && rx < 4 && t < r) {
					if (a[c[i]] == a[c[t]]) {
						int used2 = used - (1 << c[i]) - (1 << c[t]);
						ret = min(ret, rec(used2));
					}
				}
			}
		}
	}
	vis[used] = true;
	return dp[used] = ret;
}
int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		fill(vis, vis + (1 << 20), false);
		for (int j = 0; j < 20; j++) cin >> a[j];
		cout << rec((1 << 20) - 1) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 6824
final_rank: 17

code_snippet: #include<iostream>
#include<iomanip>
#include<string>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>

using namespace std;

int minimum;
vector<string> check;

void calc(int num, string cards) {

	string card;

	if(num+1 < cards.length() && num%4 < 3 && cards[num] == cards[num+1]) {
		card = cards;
		card.erase(card.begin()+num+1);
		card.erase(card.begin()+num);
		if(find(check.begin(), check.end(), card) == check.end()) {
			check.push_back(card);
			calc(0, card);
		}
	}
	if(num+4 < cards.length() && cards[num] == cards[num+4]) {
		card = cards;
		card.erase(card.begin()+num+4);
		card.erase(card.begin()+num);
		if(find(check.begin(), check.end(), card) == check.end()) {
			check.push_back(card);
			calc(0, card);
		}
	}
	if(num+3 < cards.length() && num%4 > 0 && cards[num] == cards[num+3]) {
		card = cards;
		card.erase(card.begin()+num+3);
		card.erase(card.begin()+num);
		if(find(check.begin(), check.end(), card) == check.end()) {
			check.push_back(card);
			calc(0, card);
		}
	}
	if(num+5 < cards.length() && num%4 < 3 && cards[num] == cards[num+5]) {
		card = cards;
		card.erase(card.begin()+num+5);
		card.erase(card.begin()+num);
		if(find(check.begin(), check.end(), card) == check.end()) {
			check.push_back(card);
			calc(0, card);
		}
	}

	if(num+1 < cards.length()) calc(num+1, cards);
	else if(cards.length() < minimum) minimum = cards.length();
}

int main() {
	int N;
	cin >> N;
	string cards;
	char input;

	for(int i=0; i<N; i++) {
		check.clear();
		minimum=20;
		cards = "";

		for(int j=0; j<20; j++) {
			cin >> input;
			cards.push_back(input);
		}

		for(int j=0; j<20; j++) {
			calc(j, cards);
		}
		cout << minimum << endl;
	}

	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1292
final_rank: 2

code_snippet: #include <iostream>
using namespace std;

int n;
int c[5][4];
int dp[1 << 20];

int dfs(int cnum, int rem) {
	int val[5][4];
	int id[5][4];
	
	if (dp[rem] != -1) return dp[rem];
	
	int cor = 0;
	for (int i = 0; i < 20; i++) {
		if ((rem >> i) % 2) {
			val[cor/4][cor%4] = c[i/4][i%4];
			id[cor/4][cor%4] = i;
			cor++;
		}
	}
	
	int ret = 0;
	for (int y = 0; y < 5; y++) {
		for (int x = 0; x < 4; x++) {
			if (y * 4 + x >= cnum) continue;
			for (int sy = y - 1; sy <= y + 1; sy++) {
				for (int sx = x - 1; sx <= x + 1; sx++) {
					if (sy * 4 + sx >= cnum) continue;
					if (!(0 <= sy && sy < 5 && 0 <= sx && sx < 4)) continue;
					if (sy == y && sx == x) continue;
					if (val[y][x] != val[sy][sx]) continue;
					ret = max( ret, 2 + dfs(cnum - 2, rem - (1 << id[y][x]) - (1 << id[sy][sx])) );
				}
			}
		}
	}
	return (dp[rem] = ret);
}

int main() {
	cin >> n;
	while (n--) {
		for (int i = 0; i < 20; i++) cin >> c[i/4][i%4];
		for (int i = 0; i < (1 << 20); i++) dp[i] = -1;
		cout << 20 - dfs(20, (1 << 20) - 1) << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5256
final_rank: 16

code_snippet: #include <cstdio>
#include <cstring>
#include <algorithm>
int test;
int c[11][4][5];
int res=20;

void push(int v){
	int vv=0;
	/*
	for(int i=0;i<5;i++){
		for(int j=0;j<4;j++){
			printf("%d%c",c[v][j][i],j==3?'\n':' ');
		}
	}
	printf("\n");
	*/
	for(int i=0;i<20;i++){
		if(c[v][i%4][i/4]!=0){
			c[v][vv%4][vv/4]=c[v][i%4][i/4];
			if(vv!=i){
				c[v][i%4][i/4]=0;
			}
			vv++;
		}
	}
	/*
	for(int i=0;i<5;i++){
		for(int j=0;j<4;j++){
			printf("%d%c",c[v][j][i],j==3?'\n':' ');
		}
	}
	*/
}

void dfs(int t){
	res=std::min(res,20-t*2);
	if(res==0)return;
	for(int i=0;i<5;i++){
		for(int j=0;j<4;j++){
			if(c[t][j][i]==0)continue;
			for(int k=-1;k<=1;k++){
				for(int l=-1;l<=1;l++){
					if(k==0 && l==0)continue;
					int py=i+k,px=j+l;
					if(px>=0 && px<4 && py>=0 && py<5){
						if(c[t][j][i]==c[t][px][py]){
							memset(c[t+1],0,sizeof(c[t+1]));
							for(int m=0;m<5;m++){
								for(int n=0;n<4;n++){
									if((j==n && i==m) || (px==n && py==m))continue;
									c[t+1][n][m]=c[t][n][m];
								}
							}
							push(t+1);
							dfs(t+1);
							//printf("%d %d\n",j+i*4,px+py*4);
						}
					}
				}
			}
		}
	}
}

int main(void){
	scanf("%d",&test);
	for(int ddd=0;ddd<test;ddd++){
		for(int i=0;i<5;i++){
			for(int j=0;j<4;j++){
				scanf("%d",&c[0][j][i]);
			}
		}
		res=20;
		dfs(0);
		printf("%d\n",res);
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1024
final_rank: 1

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long int uli;
map<string,int>f;

int dr[4]={1,1,1,0};
int dc[4]={-1,0,1,1};

string cmp(string s){
   string ans(20,'0');
   int cnt=0;
   for(int i=0;i<20;i++){
      while(i<20 && s[i]=='0')i++;
      if(i<20)ans[cnt++]=s[i];
   }
   return ans;
}
int solve(string s){
   if(f.count(s)!=0) return f[s];
   int ans=-1;
   int cnt=0;
   bool fnd=false;
   for(int i=0;i<5;i++){
      for(int j=0;j<4;j++){
         if(s[i*4+j]=='0')break;
         cnt++;
         for(int x=0;x<4;x++){
            int nr=i+dr[x];
            int nc=j+dc[x];
            if(0<=nr && nr<5)
            if(0<=nc && nc<4)
            if(s[i*4+j]==s[nr*4+nc]){
               fnd=true;
               string t=s;
               t[i*4+j]='0';               
               t[nr*4+nc]='0';
               int bet=solve(cmp(t));
               if(ans==-1 || bet<ans)
                  ans=bet;
            }
         }
      }
   }
   if(fnd)f[s]=ans;
   else f[s]=cnt;
   
   return f[s];
}
int main(){
//   freopen("data.in","r",stdin);
   int t,v;
   scanf("%d",&t);
   while(t--){
      string s;
      for(int i=0;i<5;i++){
         for(int j=0;j<4;j++){
            scanf("%d",&v);
            s+=string(1,'0'+v);
         }
      }
      int ans=solve(s);
      printf("%d\n",ans);
   }
   return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1656
final_rank: 6

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

using namespace std;

typedef vector<int> Vec;

void solve(Vec &s){
  int ans = 20;
  const int dx[8] = {-1,-1,-1,0,0,1,1,1};
  const int dy[8] = {-1,0,1,-1,1,-1,0,1};
  queue<Vec> Q;
  Q.push(s);
  set<Vec> visited;
  visited.insert(s);
  while(!Q.empty()){
    Vec v = Q.front(); Q.pop();
    int size = v.size();
    ans = min(ans,size);
    for(int i = 0 ; i < size ; i++){
      for(int j = 0 ; j < 8 ; j++){
        Vec next;
        int nx = i%4 + dx[j];
        int ny = i/4 + dy[j];
        if(nx < 0 || ny < 0 || nx >= min(4,size) || ny >= 5) continue;
        if(nx+ny*4 < 0 || nx+ny*4 >= size) continue;
        if(v[i] == v[nx+ny*4]){
          for(int k = 0 ; k < size ; k++){
            if(i == k || nx+ny*4 == k) continue;
            next.push_back(v[k]);
          }
          if(!visited.count(next)){
            visited.insert(next);
            Q.push(next);
          }
        }
      }
    }
  }
  cout << ans << endl;
}

int main(){
  int Tc;
  cin >> Tc;
  while(Tc--){
    Vec vec(20);
    for(int i = 0 ; i < 20 ; i++){
      cin >> vec[i];
    }
    solve(vec);
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1324
final_rank: 3

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

using namespace std;

typedef vector<int> Vec;

void solve(Vec &s){
  int ans = 20;
  const int dx[8] = {-1,-1,-1,0,0,1,1,1};
  const int dy[8] = {-1,0,1,-1,1,-1,0,1};
  queue<Vec> Q;
  Q.push(s);
  set<Vec> visited;
  visited.insert(s);
  while(!Q.empty()){
    Vec v = Q.front(); Q.pop();
    int size = v.size();
    ans = min(ans,size);
    if(size == 0) continue;
    for(int i = 0 ; i < size ; i++){
      for(int j = 0 ; j < 8 ; j++){
        Vec next;
        int nx = i%4 + dx[j];
        int ny = i/4 + dy[j];
        if(nx < 0 || ny < 0 || nx >= min(4,size) || ny >= min(5,size)) continue;
        if(nx+ny*4 < 0 || nx+ny*4 >= size) continue;
        if(v[i] == v[nx+ny*4]){
          for(int k = 0 ; k < size ; k++){
            if(i == k || nx+ny*4 == k) continue;
            next.push_back(v[k]);
          }
          if(!visited.count(next)){
            visited.insert(next);
            Q.push(next);
          }
        }
      }
    }
  }
  cout << ans << endl;
}

int main(){
  int Tc;
  cin >> Tc;
  while(Tc--){
    Vec vec(20);
    for(int i = 0 ; i < 20 ; i++){
      cin >> vec[i];
    }
    solve(vec);
  }
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1324
final_rank: 3

code_snippet: #include<stdio.h>
#include<algorithm>
using namespace std;
int b[21];
int dp[1<<20];
int dx[]={1,3,4,5};
int dy[]={1,-1,0,1};
int solve(int a){
	if(~dp[a])return dp[a];
	if(a==0)return dp[a]=0;
	int now[20];
	int sz=0;
	for(int i=0;i<20;i++){
		if(a&(1<<i))now[sz++]=i;
	}
	int ret=sz;
	for(int i=0;i<sz;i++){
		for(int j=0;j<4;j++){
			if(i+dx[j]<sz&&i%4+dy[j]<4&&0<=i%4+dy[j]&&b[now[i]]==b[now[i+dx[j]]]){
				ret=min(ret,solve(a-(1<<now[i])-(1<<now[i+dx[j]])));
			}
		}
	}
	return dp[a]=ret;
}
int main(){
	int a;
	scanf("%d",&a);
	while(a--){
		for(int i=0;i<20;i++)scanf("%d",b+i);
		for(int i=0;i<(1<<20);i++)dp[i]=-1;
		printf("%d\n",solve((1<<20)-1));
	}
}
accuracy: 1
time_ms: 10
memory_kb: 5120
final_rank: 15

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

using namespace std;

class range {
private:
  struct Iterator {
    int val;
    int operator*() {return val;}
    bool operator!=(Iterator& itr) {return val < itr.val;}
    void operator++() {++val;}
  };
  Iterator i, n;
public:
  range(int n) : i({0}), n({n}) {}
  range(int i, int n) : i({i}), n({n}) {}
  Iterator& begin() {return i;}
  Iterator& end() {return n;}
};

template<class T> inline T at(const vector<T> &v, int i) {return v[(i % (int)v.size() + v.size()) % v.size()];}

template<class T> inline bool is_max(T &a, const T &b) {return a < b ? a = b, true : false;}
template<class T> inline bool is_min(T &a, const T &b) {return a > b ? a = b, true : false;}

map<vector<int>, int> mem;

int solve(const vector<int>& v) {
  if (v.empty()) return 0;
  if (mem.count(v)) return mem[v];
  int res = v.size();
  for (int i : range((int)v.size() - 1)) if (i % 4 != 3 && v[i] == v[i + 1]) {
    vector<int> vv;
    for (int j : range(v.size())) if (j != i && j != i + 1) vv.emplace_back(v[j]);
    is_min(res, solve(vv));
  }
  for (int i : range((int)v.size() - 4)) if (v[i] == v[i + 4]) {
    vector<int> vv;
    for (int j : range(v.size())) if (j != i && j != i + 4) vv.emplace_back(v[j]);
    is_min(res, solve(vv));
  }
  for (int i : range((int)v.size() - 5)) if (i % 4 != 3 && v[i] == v[i + 5]) {
    vector<int> vv;
    for (int j : range(v.size())) if (j != i && j != i + 5) vv.emplace_back(v[j]);
    is_min(res, solve(vv));
  }
  for (int i : range((int)v.size() - 3)) if (i % 4 != 0 && v[i] == v[i + 3]) {
    vector<int> vv;
    for (int j : range(v.size())) if (j != i && j != i + 3) vv.emplace_back(v[j]);
    is_min(res, solve(vv));
  }
  return mem[v] = res;
}


int main() {
  int t;
  cin >> t;
  for (int _ : range(t)) {
    vector<int> v;
    for (int i : range(20)) {
      int c;
      cin >> c;
      v.emplace_back(c);
    }
    cout << solve(v) << endl;
  }
}
accuracy: 1
time_ms: 10
memory_kb: 1640
final_rank: 5

code_snippet: #include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
using namespace std;
#define INF 100000000
typedef long long ll;

const int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const int dy[8] = {0, 1, 1, 1, 0, -1, -1, -1};

map<vector<string>, int> m; // すでに探索済みかを確かめる

// カードをremoveした後シフトする
vector<string> shift(vector<string> s) {
    string ss;
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 4; x++) {
            if (s[y][x] != '*') ss += s[y].substr(x, 1);
        }
    }
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 4; x++) {
            if (4*y + x < ss.size()) {
                s[y][x] = ss[4*y+x];
            } else {
                s[y][x] = '*';
            }
        }
    }
    return s;
}

// sはカードの並び
int dfs(vector<string> s) {
    if (m.find(s) != m.end()) return m[s];
    int ret = 0;
    // 今のカードの枚数をチェック
    // これがretの最高値
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 4; x++) {
            if (s[y][x] != '*') ret++;
        }
    }
//    cout << "ret:" << ret << endl;
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 4; x++) {
            if (s[y][x] == '*') continue;
            for (int i = 0; i < 8; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                if (0 <= nx && nx < 4 && 0 <= ny && ny < 5 && s[y][x] == s[ny][nx]) {
                    vector<string> ss;
                    ss = s;
                    ss[y][x] = ss[ny][nx] = '*';
                    ss = shift(ss);
                    ret = min(ret, dfs(ss));
                }
            }
        }
    }
    m.insert(map<vector<string>, int>::value_type(s, ret));
    return ret;
}

int main(void) {
    int N;
    cin >> N;
    for (int i = 0; i < N; i++) {
        m.clear();
        vector<string> s;
        for (int y = 0; y < 5; y++) {
            string c;
            for (int x = 0; x < 4; x++) {
                char ch;
                cin >> ch;
                c.push_back(ch);
            }
            s.push_back(c);
        }
        cout << dfs(s) << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 1496
final_rank: 12