Problem:
Problem B:
Sort the Panels
There was an explorer Henry Nelson traveling all over the world. One day he reached an ancient
building. He decided to enter this building for his interest, but its entrance seemed to be locked
by a strange security system.
There were some black and white panels placed on a line at equal intervals in front of the
entrance, and a strange machine with a cryptogram attached. After a while, he managed to
read this cryptogram: this entrance would be unlocked when the panels were rearranged in a
certain order, and he needed to use this special machine to change the order of panels.
All he could do with this machine was to swap arbitrary pairs of panels. Each swap could be
performed by the following steps:
move the machine to one panel and mark it;
move the machine to another panel and again mark it; then
turn on a special switch of the machine to have the two marked panels swapped.
It was impossible to have more than two panels marked simultaneously. The marks would be
erased every time the panels are swapped.
He had to change the order of panels by a number of swaps to enter the building. Unfortunately,
however, the machine was so heavy that he didn’t want to move it more than needed. Then
which steps could be the best?
Your task is to write a program that finds the minimum cost needed to rearrange the panels,
where moving the machine between adjacent panels is defined to require the cost of one. You
can arbitrarily choose the initial position of the machine, and don’t have to count the cost for
moving the machine to that position.
Input
The input consists of multiple datasets.
Each dataset consists of three lines. The first line contains an integer
N
, which indicates the
number of panels (2 ≤
N
≤ 16). The second and third lines contain
N
characters each,
and describe the initial and final orders of the panels respectively. Each character in these descriptions is either ‘B’ (for black) or ‘W’ (for white) and denotes the color of the panel. The
panels of the same color should
not
be distinguished.
The input is terminated by a line with a single zero.
Output
For each dataset, output the minimum cost on a line. You can assume that there is at least one
way to change the order of the panels from the initial one to the final one.
Sample Input
4
WBWB
BWBW
8
WWWWBWBB
WWBBWBWW
0
Output for the Sample Input
3
9

Submitted solutions:

code_snippet: #include <cstring>
#include <iostream>
#include <string>

using namespace std;

int getStat(string arg) {
	int ret = 0;
	for(char ch: arg)
		if(ch == 'B') ret = ret * 2 + 1;
		else ret *= 2;
	return ret;
}

int dp[1 << 16][16];
int n, goal;

int getAns(int stat, int machine) {
	int &ret = dp[stat][machine];
	if(ret != -1) return ret;

	ret = 0;
	if(stat != goal) {
		ret = (1 << 29);
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if((stat & (1 << i)) > 0 != (stat & (1 << j)) > 0) {
					if(	(stat & (1 << i)) != (goal & (1 << i)) and
						(stat & (1 << j)) != (goal & (1 << j))) {
						ret = min(ret, getAns(stat ^ (1 << i) ^ (1 << j), j) + abs(machine - i) + abs(i - j));
					}
				}
			}
		}
	}

	return ret;
}

int main(void) {
	while(cin >> n, n > 0) {
		string start, end;
		cin >> start >> end;
		goal = getStat(end);
		memset(dp, -1, sizeof(dp));
		int ans = (1 << 30);
		for(int i = 0; i < n; i++)
			ans = min(ans, getAns(getStat(start), i));
		cout << ans << "\n";
	}

	return 0;
}
accuracy: 1
time_ms: 170
memory_kb: 7464
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f000000;
bool cmp(int x, int y) {
    return __builtin_popcount(x) < __builtin_popcount(y);
}
int main() {
    int n;
    while (true) {
        scanf("%d", &n);
        if (!n) {
            fflush(stdout);
            exit(0);
        }
        char s[18], t[18];
        scanf("%s", s);
        scanf("%s", t);
        vector<vector<int> > dp(1 << n, vector<int>(n, inf));
        int mask = 0;
        for (int i = 0; i < n; ++i) {
            mask |= (s[i] == t[i]) << i;
        }
        fill(dp[mask].begin(), dp[mask].end(), 0);
        vector<int> masks;
        for (int i = 0; i < (1 << n); ++i) {
            masks.push_back(i);
        }
        sort(masks.begin(), masks.end(), cmp);
        for (int z = 0; z < (1 << n); ++ z) { int cur = masks[z];
            for (int pos = 0; pos < n; ++pos) {
                if (dp[cur][pos] == inf) continue;
                for (int i = 0; i < n; ++i) {
                    if (cur >> i & 1) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((cur >> j & 1) || s[i] == s[j]) continue;
                        int after = cur | (1 << i) | (1 << j);
                        int dist = abs(pos - j) + abs(j - i);
                        dp[after][i] = min(dp[after][i], dp[cur][pos] + dist);
                    }
                }
            }
        }
        printf("%d\n", *min_element(dp[(1 << n) - 1].begin(), dp[(1 << n) - 1].end()));
    }
}
accuracy: 1
time_ms: 300
memory_kb: 9892
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f000000;
bool cmp(int x, int y) {
    return __builtin_popcount(x) < __builtin_popcount(y);
}
int main() {
    int n;
    while (cin >> n) {
        if (!n) {
            fflush(stdout);
            return 0;
        }
        string s, t;
        cin >> s >> t;
        vector<vector<int> > dp(1 << n, vector<int>(n, inf));
        int mask = 0;
        for (int i = 0; i < n; ++i) {
            mask |= (s[i] == t[i]) << i;
        }
        fill(dp[mask].begin(), dp[mask].end(), 0);
        vector<int> masks;
        for (int i = 0; i < (1 << n); ++i) {
            masks.push_back(i);
        }
        sort(masks.begin(), masks.end(), cmp);
        for (int cur : masks) {
            for (int pos = 0; pos < n; ++pos) {
                if (dp[cur][pos] == inf) continue;
                for (int i = 0; i < n; ++i) {
                    if (cur >> i & 1) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((cur >> j & 1) || s[i] == s[j]) continue;
                        int after = cur | (1 << i) | (1 << j);
                        int dist = abs(pos - j) + abs(j - i);
                        dp[after][i] = min(dp[after][i], dp[cur][pos] + dist);
                    }
                }
            }
        }
        printf("%d\n", *min_element(dp[(1 << n) - 1].begin(), dp[(1 << n) - 1].end()));
    }
}
accuracy: 1
time_ms: 210
memory_kb: 10596
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f000000;
bool cmp(int x, int y) {
    return __builtin_popcount(x) < __builtin_popcount(y);
}
int main() {
    int n;
    while (cin >> n) {
        if (!n) return 0;
        string s, t;
        cin >> s >> t;
        vector<vector<int> > dp(1 << n, vector<int>(n, inf));
        int mask = 0;
        for (int i = 0; i < n; ++i) {
            mask |= (s[i] == t[i]) << i;
        }
        fill(dp[mask].begin(), dp[mask].end(), 0);
        vector<int> masks;
        for (int i = 0; i < (1 << n); ++i) {
            masks.push_back(i);
        }
        sort(masks.begin(), masks.end(), cmp);
        for (int cur : masks) {
            for (int pos = 0; pos < n; ++pos) {
                if (dp[cur][pos] == inf) continue;
                for (int i = 0; i < n; ++i) {
                    if (cur >> i & 1) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((cur >> j & 1) || s[i] == s[j]) continue;
                        int after = cur | (1 << i) | (1 << j);
                        int dist = abs(pos - j) + abs(j - i);
                        dp[after][i] = min(dp[after][i], dp[cur][pos] + dist);
                    }
                }
            }
        }
        printf("%d\n", *min_element(dp[(1 << n) - 1].begin(), dp[(1 << n) - 1].end()));
    }
}
accuracy: 1
time_ms: 230
memory_kb: 10356
final_rank: 12

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f000000;
bool cmp(int x, int y) {
    return __builtin_popcount(x) < __builtin_popcount(y);
}
int main() {
    cin.tie(0);
    ios_base::sync_with_stdio(0);
    int n;
    while (cin >> n) {
        if (!n) return 0;
        string s, t;
        cin >> s >> t;
        vector<vector<int> > dp(1 << n, vector<int>(n, inf));
        int mask = 0;
        for (int i = 0; i < n; ++i) {
            mask |= (s[i] == t[i]) << i;
        }
        fill(dp[mask].begin(), dp[mask].end(), 0);
        vector<int> masks;
        for (int i = 0; i < (1 << n); ++i) {
            masks.push_back(i);
        }
        sort(masks.begin(), masks.end(), cmp);
        for (int cur : masks) {
            for (int pos = 0; pos < n; ++pos) {
                if (dp[cur][pos] == inf) continue;
                for (int i = 0; i < n; ++i) {
                    if (cur >> i & 1) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((cur >> j & 1) || s[i] == s[j]) continue;
                        int after = cur | (1 << i) | (1 << j);
                        int dist = abs(pos - j) + abs(j - i);
                        dp[after][i] = min(dp[after][i], dp[cur][pos] + dist);
                    }
                }
            }
        }
        cout << *min_element(dp[(1 << n) - 1].begin(), dp[(1 << n) - 1].end()) << '\n';
    }
}
accuracy: 1
time_ms: 230
memory_kb: 10484
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f000000;
bool cmp(int x, int y) {
    return __builtin_popcount(x) < __builtin_popcount(y);
}
int dp[1 << 16][16];
int main() {
    int n;
    while (true) {
        cin >> n;
        if (!n) return 0;
        string s, t;
        cin >> s >> t;
        int mask = 0, c = 0;
        for (int i = 0; i < n; ++i) {
            mask |= (s[i] == t[i]) << i;
        }
        c = __builtin_popcount(mask) % 2;
        for (int i = 0; i < (1 << n); ++i) {
            for (int j = 0; j < n; ++j) {
                dp[i][j] = inf;
            }
        }
        for (int i = 0; i < n; ++i) dp[mask][i] = 0;
        vector<int> masks;
        for (int i = 0; i < (1 << n); ++i) {
            if (__builtin_popcount(i) % 2 == c) masks.push_back(i);
        }
        sort(masks.begin(), masks.end(), cmp);
        for (int cur : masks) {
            for (int pos = 0; pos < n; ++pos) {
                if (dp[cur][pos] == inf) continue;
                for (int i = 0; i < n; ++i) {
                    if (cur >> i & 1) continue;
                    for (int j = 0; j < n; ++j) {
                        if ((cur >> j & 1) || s[i] == s[j]) continue;
                        int after = cur | (1 << i) | (1 << j);
                        int dist = abs(pos - j) + abs(j - i);
                        dp[after][i] = min(dp[after][i], dp[cur][pos] + dist);
                    }
                }
            }
        }
        int ans = inf;
        for (int i = 0; i < n; ++i) ans = min(ans, dp[(1 << n) - 1][i]);
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 120
memory_kb: 7552
final_rank: 9

code_snippet: #include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>
 
using namespace std;
 
#define FOR(i,k,n) for(int i=(k); i<(int)n; ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
 
template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; }
 
typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;
int N;
string s, g;
int dp[1<<16][16];
int dfs(int S, int u){
  if(S == (1<<N) - 1) return 0;
  if(dp[S][u] != -1) return dp[S][u];
  int res = INF;
  REP(i, N)REP(j, N) if(i != j && (S >> i & 1) == 0 && (S >> j & 1) == 0 && g[i] != g[j]){
    res = min(res, abs(u - i) + abs(i - j) + dfs(S | 1 << i | 1 << j, j));
  }
  return dp[S][u] = res;
}
int main(){
  while(cin>>N && N){
    cin>>s>>g;
    REP(S, 1<<N) REP(p, N) dp[S][p] = -1;
    int S = 0;
    REP(i, N) if(s[i] == g[i]) S |= 1<<i;
    int ans = INF;
    REP(i, N) ans = min(ans, dfs(S, i));
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 190
memory_kb: 7176
final_rank: 5

code_snippet: #include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;

struct aa {
	bitset<16>bs;
	int cost;
	int now;
};
class Compare {
public:
	bool operator()(const aa&l, const aa&r) {
		return l.cost>r.cost;
	}
};

int main() {
	while (true) {
		int N;cin>>N;
		if(!N)break;
		string a,b;cin>>a>>b;
		bitset<16>start,goal;
		for (int i = 0; i < N; ++i) {
			if(a[i]=='B')start[i]=true;
			if(b[i]=='B')goal[i]=true;
		}
		vector<vector<int>>memo((1<<N),vector<int>(N,1e9));
		for (int i = 0; i < N; ++i) {
			memo[start.to_ulong()][i]=0;
		}

		priority_queue<aa,vector<aa>,Compare>que;
		for (int i = 0; i < N; ++i) {
			que.push(aa{ start,0,i });
		}

		int ans=1e9;
		while (!que.empty()) {
			auto atop(que.top());
			que.pop();

			bitset<16>bs(atop.bs);
			const int cost(atop.cost);
			const int now(atop.now);
			if (bs == goal) {
				ans=min(ans,cost);
			}
			for (int i = 0; i < N; ++i) {
				int u=bs[now];
				bs[now]=bs[i];
				bs[i]=u;
				const int next_cost=cost+(abs(now-i));
				if (memo[bs.to_ulong()][i] > next_cost) {
					memo[bs.to_ulong()][i]=next_cost;
					que.push(aa{ bs,next_cost,i });
				}
				u = bs[now];
				bs[now] = bs[i];
				bs[i] = u;
			}
			for (int i = 0; i < N; ++i) {
				const int next_cost = cost + (abs(now - i));
				if (memo[bs.to_ulong()][i] > next_cost) {
					memo[bs.to_ulong()][i] = next_cost;
					que.push(aa{ bs,next_cost,i });
				}
			}
		}
		cout<<ans<<endl;
	}


	return 0;
}
accuracy: 1
time_ms: 1080
memory_kb: 15780
final_rank: 15

code_snippet: #include <functional>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

using namespace std;

int main()
{
    while (true) {
        int n;
        cin >> n;
        if (n == 0) {
            return 0;
        }

        string init;
        string final;
        cin >> init;
        cin >> final;

        auto encode = [](const string& s) {
            int r = 0b0;
            for (int i = 0; i < s.size(); ++i) {
                if (i != 0) {
                    r <<= 1;
                }
                if (s[i] == 'B') {
                    r |= 0b1;
                }
            }
            return r;
        };

        auto target = encode(final);
        auto start = encode(init);

        vector<vector<int>> memo(n, vector<int>(1 << n, -1));
        // p ??????????????´?????¶?????? s ?????¨??????????°???????????????????
        function<int(int, int)> f = [&f, &memo, n, start](int p, int s) -> int {
            if (memo[p][s] != -1) {
                return memo[p][s];
            }

            // ??????????????´????????????
            if (s == 0) {
                return 0;
            }

            int min_ = numeric_limits<int>::max();
            for (int i = 0; i < n; ++i) {
                // i ??????????????§????????´????????????
                if (((s >> i) & 1) == 0) {
                    continue;
                }
                for (int j = 0; j < n; ++j) {
                    if (i == j) {
                        continue;
                    }
                    // j ??????????????§????????´????????????
                    else if ((s >> j & 1) == 0) {
                        continue;
                    }
                    // ?????????????????\????????????????°???????????????????
                    else if ((((start >> i) & 1) ^ ((start >> j) & 1)) == 0) {
                        continue;
                    }
                    else {
                        // p ?????? i ?????§?????£???, i ?????? j ?????§??????
                        auto cost = abs(i - p) + abs(j - i);
                        min_ = min(min_, cost + f(j, s ^ (1 << i) ^ (1 << j)));
                    }
                }
            }
            memo[p][s] = min_;

            return min_;
        };

        int min_ = numeric_limits<int>::max();
        // ????????????????????????????????????
        for (int i = 0; i < n; ++i) {
            min_ = min(min_, f(i, start ^ target));
        }
        cout << min_ << endl;
    }
}
accuracy: 1
time_ms: 150
memory_kb: 7332
final_rank: 7

code_snippet: #include <bitset>
#include <functional>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

using namespace std;

int main()
{
    while (true) {
        int n;
        cin >> n;
        if (n == 0) {
            return 0;
        }

        string init;
        string final;
        cin >> init;
        cin >> final;

        auto encode = [](const string& s) {
            int r = 0b0;
            for (int i = 0; i < s.size(); ++i) {
                if (i != 0) {
                    r <<= 1;
                }
                if (s[i] == 'B') {
                    r |= 0b1;
                }
            }
            return r;
        };

        auto pow = [](int b, int e) {
            int r = 1;
            for (int i = 0; i < e; ++i) {
                r *= b;
            }
            return r;
        };

        auto target = encode(final);
        auto start = encode(init);

        vector<vector<int>> memo(n, vector<int>(pow(2, n), -1));
        // p ??????????????´?????¶?????? s ?????¨??????????°???????????????????
        function<int(int, int)> f = [&f, &memo, n, &pow, start](int p,
                                                                int s) -> int {
            if (memo[p][s] != -1) {
                return memo[p][s];
            }

            // ??????????????´????????????
            if (s == 0) {
                return 0;
            }

            int min_ = numeric_limits<int>::max();
            int pp = -1;
            for (int i = 0; i < n; ++i) {
                // i ??????????????§????????´????????????
                if (((s >> i) & 1) == 0) {
                    continue;
                }
                for (int j = 0; j < n; ++j) {
                    if (i == j) {
                        continue;
                    }
                    // j ??????????????§????????´????????????
                    else if ((s >> j & 1) == 0) {
                        continue;
                    }
                    // ?????????????????\????????????????°???????????????????
                    else if ((((start >> i) & 1) ^ ((start >> j) & 1)) == 0) {
                        continue;
                    }
                    else {
                        // p ?????? i ?????§?????£???, i ?????? j ?????§??????
                        auto cost = abs(i - p) + abs(j - i);
                        auto ss = s;
                        ss ^= 1 << i;
                        ss ^= 1 << j;
                        auto min__ = min_;
                        min_ = min(min_, cost + f(j, ss));
                        if (min__ != min_) {
                            pp = p;
                        }
                    }
                }
            }
            memo[pp][s] = min_;

            return min_;
        };

        int min_ = numeric_limits<int>::max();
        for (int i = 0; i < n; ++i) {
            min_ = min(min_, f(i, start ^ target));
        }
        cout << min_ << endl;
    }
}
accuracy: 1
time_ms: 160
memory_kb: 7280
final_rank: 6

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <fstream>
#include <functional>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

using namespace std;

int main()
{
    //ifstream cin("/Volumes/env1/work/aoj/2040/a");
    while (true) {
        int n;
        cin >> n;
        if (n == 0) {
            return 0;
        }

        string init;
        string final;
        cin >> init;
        cin >> final;

        auto encode = [](const string& s) {
            int r = 0b0;
            for (int i = 0; i < s.size(); ++i) {
                if (i != 0) {
                    r <<= 1;
                }
                if (s[i] == 'B') {
                    r |= 0b1;
                }
            }
            return r;
        };

        auto pow = [](int b, int e) {
            int r = 1;
            for (int i = 0; i < e; ++i) {
                r *= b;
            }
            return r;
        };

        auto target = encode(final);
        auto start = encode(init);

        vector<vector<int>> memo(n, vector<int>(pow(2, n), -1));
        // p ??????????????´?????¶?????? s ?????¨??????????°???????????????????
        function<int(int, int)> f = [&f, &memo, n, &pow, start](int p,
                                                                int s) -> int {
            //cout << static_cast<bitset<8>>(s) << endl;
            if (memo[p][s] != -1) {
                //cout << "memo1" << p << ' ' << s << endl;
                return memo[p][s];
            }

            // ??????????????´????????????
            if (s == 0) {
                return 0;
            }

            int min_ = numeric_limits<int>::max();
            int pp = -1;
            for (int i = 0; i < n; ++i) {
                // i ??????????????§????????´????????????
                if (((s >> i) & 1) == 0) {
                    continue;
                }
                for (int j = 0; j < n; ++j) {
                    if (i == j) {
                        continue;
                    }
                    // j ??????????????§????????´????????????
                    else if ((s >> j & 1) == 0) {
                        continue;
                    }
                    // ?????????????????\????????????????°???????????????????
                    else if ((((start >> i) & 1) ^ ((start >> j) & 1)) == 0) {
                        continue;
                    }
                    else {
                        // p ?????? i ?????§?????£???, i ?????? j ?????§??????
                        auto cost = abs(i - p) + abs(j - i);
                        auto ss = s;
                        ss ^= 1 << i;
                        ss ^= 1 << j;
                        //cout << "pos: " << p << " swap " << i << ", " << j
                        //     << ": " << static_cast<bitset<8>>(s) << " to "
                        //     << static_cast<bitset<8>>(ss) << " cost " << cost
                        //     << endl;
                        auto min__ = min_;
                        min_ = min(min_, cost + f(j, ss));
                        if (min__ != min_) {
                            pp = p;
                        }
                    }
                }
            }
            //cout << "write memo " << pp << " " << static_cast<bitset<8>>(s) << endl;
            memo[pp][s] = min_;
            assert(min_ != -1);

            return min_;
        };

        int min_ = numeric_limits<int>::max();
        for (int i = 0; i < n; ++i) {
            min_ = min(min_, f(i, start ^ target));
        }
        cout << min_ << endl;
    }
}
accuracy: 1
time_ms: 150
memory_kb: 7348
final_rank: 8

code_snippet: #include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
#include <string>
#include <map>
#include <queue>
#include <functional>
#include <assert.h>
using namespace std;
inline int pack(int p, int ps, int n) {
  return (p << n) | ps;
}
int main(int argc, char *argv[])
{
  for(;;) {
    int n;
    cin >> n;
    if(n==0) break;
    string sa, sb;
    getline(cin, sa);
    getline(cin, sa);
    getline(cin, sb);
    auto conv = [n](string &s) {
      int r = 0;
      for(int i = 0; i < n; i++) {
        r = (r<<1) + (s[i] == 'W' ? 1 : 0); 
      }
      return r;
    };
    const int a = conv(sa);
    const int b = conv(sb);
    //cout << "a = " << static_cast<std::bitset<8> >(a) << endl;
    //cout << "b = " << static_cast<std::bitset<8> >(b) << endl;
    // better DP: state = (head-pos, difference)
    vector<int> ds(n<<n, -1);
    function<int(int)> rec = [&rec,&b,&n,&ds](const int v){
      if(ds[v] >= 0) return ds[v];
      const int p = v >> n;
      const int s = v & ((1<<n) - 1);
      if(s == 0) return 0;
      int e = 10000000;
      for(int i = 0; i < n; i++) {
        if((s & (1<<i)) == 0) continue;
        for(int j = 0; j < n; j++) {
          if(i == j) continue;
          if((s & (1<<j)) == 0) continue;
          if((((b>>i) ^ (b>>j))&1) == 0) continue;
          const int c = abs(i - p) + abs(j - i);
          const int u = pack(j, s ^ (1<<i) ^ (1<<j), n); // swap
          e = min(e, c + rec(u));
        }
      }
      ds[v] = e;
      return e;
    };
    int e = 10000000;
    for(int i = 0; i < n; i++) {
      e = min(e, rec(pack(i, a^b, n)));
    }
    cout << e << endl;
/*  // naive Dijkstra search: state = (head-pos, panels)
    vector<int> ds(n<<n, 100000000);
    priority_queue<pair<int,int>> que;
    for(int i = 0; i < n; i++) {
      int v = pack(i, a, n);
      ds[v] = 0;
      que.push(make_pair(-ds[v], v));
      
    }
    vector<bool> done(n, false);
    int rest = n;
    while(que.size() > 0) {
      auto dv = que.top(); que.pop();
      const int v = dv.second;
      const int d = -dv.first;
      const int p = v >> n;
      const int s = v & ((1<<n) - 1);
      //cout << "popped: " << static_cast<std::bitset<8> >(s) << " at " << p << " with cost " << d << endl;
      if(s == b) {
        if(!done[p]) {
          done[p] = true;
          rest--;
        }
        if(rest == 0) {
          int e = d;
          for(int i = 0; i < n; i++) {
            e = min(e, ds[pack(i, b, n)]);
          }
          cout << e << endl;
          break;
        }
      }
      // generate all possible transitions: marking i, and then j.
      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
          if(i == j) continue;
          if((((s>>i) ^ (s>>j))&1) == 0) continue;
          const int c = abs(i - p) + abs(j - i);
          const int u = pack(j, s ^ (1<<i) ^ (1<<j), n); // swap
          if(ds[u] > d + c) {
            ds[u] = d + c;
            que.push(make_pair(-ds[u], u));
            //cout << " to " << i << " and " << j << " cost " << ds[u] << " for " << static_cast<std::bitset<8> >(u) << endl;
          }
        }
      }
    }
*/
  }
  return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 7088
final_rank: 2

code_snippet: #include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
#include <string>
#include <map>
#include <queue>
#include <functional>
#include <assert.h>
using namespace std;
inline int pack(int p, int ps, int n) {
  return (p << n) | ps;
}
int main(int argc, char *argv[])
{
  for(;;) {
    int n;
    cin >> n;
    if(n==0) break;
    string sa, sb;
    getline(cin, sa);
    getline(cin, sa);
    getline(cin, sb);
    auto conv = [n](string &s) {
      int r = 0;
      for(int i = 0; i < n; i++) {
        r = (r<<1) + (s[i] == 'W' ? 1 : 0); 
      }
      return r;
    };
    int a = conv(sa);
    int b = conv(sb);
    //cout << "a = " << static_cast<std::bitset<8> >(a) << endl;
    //cout << "b = " << static_cast<std::bitset<8> >(b) << endl;

    // state = (pos, panels)
    vector<int> ds(n<<n, 100000000);
    priority_queue<pair<int,int>> que;
    for(int i = 0; i < n; i++) {
      int v = pack(i, a, n);
      ds[v] = 0;
      que.push(make_pair(-ds[v], v));
      
    }
    vector<bool> done(n, false);
    int rest = n;
    while(que.size() > 0) {
      auto dv = que.top(); que.pop();
      const int v = dv.second;
      const int d = -dv.first;
      const int p = v >> n;
      const int s = v & ((1<<n) - 1);
      //cout << "popped: " << static_cast<std::bitset<8> >(s) << " at " << p << " with cost " << d << endl;
      if(s == b) {
        if(!done[p]) {
          done[p] = true;
          rest--;
        }
        if(rest == 0) {
          int e = d;
          for(int i = 0; i < n; i++) {
            e = min(e, ds[pack(i, b, n)]);
          }
          cout << e << endl;
          break;
        }
      }
      // generate all possible transitions: marking i, and then j.
      for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
          if(i == j) continue;
          if((((s>>i) ^ (s>>j))&1) == 0) continue;
          const int c = abs(i - p) + abs(j - i);
          const int u = pack(j, s ^ (1<<i) ^ (1<<j), n); // swap
          if(ds[u] > d + c) {
            ds[u] = d + c;
            que.push(make_pair(-ds[u], u));
            //cout << " to " << i << " and " << j << " cost " << ds[u] << " for " << static_cast<std::bitset<8> >(u) << endl;
          }
        }
      }
    }
  }
  return 0;
}
accuracy: 1
time_ms: 5380
memory_kb: 13796
final_rank: 18

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


struct Info{
	Info(int arg_state,int arg_sum_cost,int arg_loc){
		state = arg_state;
		sum_cost = arg_sum_cost;
		loc = arg_loc;
	}
	bool operator<(const struct Info &arg) const{
		return sum_cost > arg.sum_cost;
	}
	int state,sum_cost,loc;
};


int N;
int POW[17],dp[65536][16],start_state,goal_state,ans_num[16];
char buf_start[17],buf_goal[17];

void func(){

	scanf("%s",buf_start);

	start_state = 0;

	for(int i = 0; buf_start[i] != '\0'; i++){
		if(buf_start[i] == 'B'){
			start_state += POW[i];
		}
	}

	scanf("%s",buf_goal);

	goal_state = 0;

	for(int i = 0; buf_goal[i] != '\0'; i++){
		if(buf_goal[i] == 'B'){
			goal_state += POW[i];
			ans_num[i] = 1;
		}else{
			ans_num[i] = 0;
		}
	}

	if(start_state == goal_state){
		printf("0\n");
		return;
	}

	for(int state = 0; state < POW[N]; state++){
		for(int loc = 0; loc < N; loc++)dp[state][loc] = BIG_NUM;
	}

	priority_queue<Info> Q;
	for(int loc = 0; loc < N; loc++){
		dp[start_state][loc] = 0;
		Q.push(Info(start_state,0,loc));
	}

	int ans = BIG_NUM;
	int next_state,num_1,num_2,tmp_cost;

	while(!Q.empty()){

		if(Q.top().state == goal_state){
			ans = min(ans,Q.top().sum_cost);
			Q.pop();
		}else if(Q.top().sum_cost > dp[Q.top().state][Q.top().loc]){
			Q.pop();
		}else{

			for(int mark_1 = 0; mark_1 < N; mark_1++){
				for(int mark_2 = 0; mark_2 < N; mark_2++){
					if(mark_1 == mark_2)continue;

					if(Q.top().state & (1 << mark_1)){
						num_1 = 1;
					}else{
						num_1 = 0;
					}

					if(Q.top().state & (1 << mark_2)){
						num_2 = 1;
					}else{
						num_2 = 0;
					}

					if(num_1 == num_2)continue;

					if(num_1 == ans_num[mark_1] && num_2 == ans_num[mark_2])continue;

					if(num_1 == 1){
						next_state = Q.top().state-POW[mark_1]+POW[mark_2];
					}else{ //num_2 == 1
						next_state = Q.top().state+POW[mark_1]-POW[mark_2];
					}

					tmp_cost = abs(mark_1-Q.top().loc)+abs(mark_2-mark_1);

					if(dp[next_state][mark_2] > Q.top().sum_cost+tmp_cost){
						dp[next_state][mark_2] = Q.top().sum_cost+tmp_cost;
						Q.push(Info(next_state,Q.top().sum_cost+tmp_cost,mark_2));
					}
				}
			}
			Q.pop();
		}
	}

	printf("%d\n",ans);
}

int main(){

	for(int i = 0; i < 17; i++)POW[i] = pow(2,i);

	while(true){
		scanf("%d",&N);
		if(N == 0)break;

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 3240
memory_kb: 16396
final_rank: 17

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

using namespace std;

#define int long long
#define all(v) begin(v), end(v)
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define reps(i, s, n) for(int i = (int)(s); i < (int)(n); i++)

template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;}

using pint = pair<int, int>;
using tint = tuple<int, int, int>;
using vint = vector<int>;

const int inf = 1LL << 55;
const int mod = 1e9 + 7;

int N;
string s, t;
int mincost[16][1<<16];
int sbit, tbit;

struct State {
  int now, cost, bit;
  State(){}
  State(int now, int cost, int bit):now(now), cost(cost), bit(bit){}
  bool operator < (const State &st) const {
    return cost > st.cost;
  }
};

int dijkstra(int pos) {
  fill(mincost[0], mincost[16], inf);
  mincost[pos][sbit] = 0;
  priority_queue<State> que;
  que.emplace(pos, 0, sbit);
  while(!que.empty()) {
    State st = que.top(); que.pop();
    int now = st.now, cost = st.cost, bit = st.bit;
    //cout << now << " "<< cost << endl;
    //rep(i, N) cout << (int)((bit>>i)&1);
    //cout << endl;
    if(bit == tbit) return cost;
    if(mincost[now][bit] < cost) continue;
    rep(i, N) if(i != now) {
      int ncost = cost + abs(i-now);
      if(ncost < mincost[i][bit]) {
	mincost[i][bit] = ncost;
	que.emplace(i, ncost, bit);
      }
      if(((bit>>i)&1) == ((bit>>now)&1)) continue;
      int nbit = bit^(1<<i)^(1<<now);
      //rep(i, N) cout << (int)((bit>>i)&1);cout<<endl;
      //cout<<now<<" "<<i<<endl;
      //cout << (int)((bit>>i)&1) << " "<<(int)((bit>>now)&1) << endl;
      //cout<<(int)(((bit>>i)&1) == ((bit>>now)&1)) << endl;
      //rep(i, N) cout << (int)((nbit>>i)&1);cout<<endl;
      //assert(__builtin_popcount(nbit) == __builtin_popcount(bit));
      if(ncost < mincost[i][nbit]) {
	mincost[i][nbit] = ncost;
	que.emplace(i, ncost, nbit);
      }
    }
  }
  return inf;
}

signed main()
{
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  while(cin >> N, N) {
    cin >> s >> t;
    sbit = tbit = 0;
    rep(i, N) if(s[i] == 'B') sbit |= 1<<i;
    rep(i, N) if(t[i] == 'B') tbit |= 1<<i;
    int ans = inf;
    rep(i, N) {
      chmin(ans, dijkstra(i));
      //cout<<ans<<endl;//exit(0);
    }
    cout << ans << endl;
  }

  return 0;
}
accuracy: 1
time_ms: 7490
memory_kb: 21180
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;
int dp[1<<16][16],n;
int main() {
  while(cin >> n && n) {
    string s,s2;cin>>s>>s2;
    int r=0;
    for(int t=0;t<(1<<n);t++)for(int i=0;i<n;i++)dp[t][i]=1<<29;
    for(int i=0;i<n;i++)if(s[i]==s2[i]) r|=1<<i;
    for(int i=0;i<n;i++)dp[r][i]=0;
    for(int t=0;t<(1<<n);t++) {
      for(int i=0;i<n;i++) {
        if(dp[t][i]==1<<29) continue;
        for(int j=0;j<n;j++) {
          if(t&(1<<j)) continue;
          for(int k=j+1;k<n;k++) {
            if(t&(1<<k)||s[j]==s[k]) continue;
            dp[t|(1<<j)|(1<<k)][j]=min(dp[t|(1<<j)|(1<<k)][j],dp[t][i]+abs(i-k)+abs(k-j));
            dp[t|(1<<j)|(1<<k)][k]=min(dp[t|(1<<j)|(1<<k)][k],dp[t][i]+abs(i-j)+abs(j-k));
          }
        }
      }
    }
    int ans=1<<29;
    for(int i=0;i<n;i++)ans=min(ans,dp[(1<<n)-1][i]);
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 7092
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
int dp[1<<16][16],n;
int main() {
  while(cin >> n && n) {
    string s,s2;cin>>s>>s2;
    int r=0;
    for(int t=0;t<(1<<n);t++)for(int i=0;i<n;i++)dp[t][i]=1<<29;
    for(int i=0;i<n;i++)if(s[i]==s2[i]) r|=1<<i;
    for(int i=0;i<n;i++)dp[r][i]=0;
    for(int t=0;t<(1<<n);t++) {
      for(int i=0;i<n;i++) {
        if(dp[t][i]==1<<29) continue;
        string e="";
        for(int j=0; j<n;j++) {
          if(t&(1<<j)) e+='1';else e+='0';
        }
        for(int j=0;j<n;j++) {
          if(t&(1<<j)) continue;
          for(int k=j+1;k<n;k++) {
            if(t&(1<<k)||s[j]==s[k]) continue;
            dp[t|(1<<j)|(1<<k)][j]=min(dp[t|(1<<j)|(1<<k)][j],dp[t][i]+abs(i-k)+abs(k-j));
            dp[t|(1<<j)|(1<<k)][k]=min(dp[t|(1<<j)|(1<<k)][k],dp[t][i]+abs(i-j)+abs(j-k));
          }
        }
      }
    }
    int ans=1<<29;
    for(int i=0;i<n;i++)ans=min(ans,dp[(1<<n)-1][i]);
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 120
memory_kb: 7236
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
string A,B;
int n,Ab,Bb;

int Bit(int bit ,int i,int x){
  while((bit>>i&1)!=x)bit ^= 1<<i;
  return bit;
}

int mem[16][1<<16],used[16][1<<16];
int dep = 0;
int dfs(short pos,int bit){
  cout<<  dep++ <<endl;
  if(bit ==Bb) return 0;
  if(used[pos][bit]++) return mem[pos][bit];
  
  int &res = mem[pos][bit] = 1e9;
  for(int i=0;i<n;i++)
    for(int j=0;j<n;j++){
      int nbit = bit;
      nbit = Bit(nbit,i,bit>>j&1);
      nbit = Bit(nbit,j,bit>>i&1);
      res = min(res,abs(pos-i)+abs(i-j)+dfs(j,nbit));
    }
  cout<<dep<<endl;
  return mem[pos][bit];
}


typedef pair<int,int> P;
typedef pair<int,P> PP;
int bfs(){
  for(int j=0;j<16;j++) 
    for(int i=0;i<(1<<16);i++)mem[j][i] = 1e9;
  
  priority_queue<PP,vector<PP>,greater<PP> > Q;
  for(int i=0;i<n;i++) Q.push(PP(0,P(i,Ab))),mem[i][Ab] = 0;
  while(!Q.empty()){
    PP t = Q.top();Q.pop();
    int cost = t.first;
    int pos = t.second.first;
    int bit = t.second.second;
    if(bit == Bb) return cost;
    if(mem[pos][bit]<cost)continue;
    
    for(int i=0;i<n;i++)
      for(int j=0;j<n;j++){
	int nbit = bit;
	nbit = Bit(nbit,i,bit>>j&1);
	nbit = Bit(nbit,j,bit>>i&1);
	int ncost = cost+abs(pos-i)+abs(i-j);
	if(ncost >= mem[j][nbit])continue;
	Q.push(PP(ncost,P(j,nbit)));
	mem[j][nbit] = ncost;
      }
  }
  assert(0);  
}


int main(){
 
  while(cin>>n,n){
    cin>>A>>B;
    
    Ab = Bb = 0;
    for(int i=0;i<n;i++)Ab|=(A[i]=='W')<<i, Bb|=(B[i]=='W')<<i;
    
    memset(used,0,sizeof(used));
    int ans = 1e9;
    //for(int i=0;i<n;i++) ans=min(ans,dfs(i,Ab));
    //cout<<ans<<endl;
    cout<<bfs()<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 3040
memory_kb: 21368
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
int dp[1<<16][16];
int main() {
  int n;
  while(cin >> n && n) {
    string s,s2;
    cin >> s >> s2;
    int r=0;
    for(int t=0;t<(1<<n);t++)for(int i=0;i<n;i++)dp[t][i]=1<<29;
    for(int i=0;i<n;i++)if(s[i]==s2[i]) r|=1<<i;
    for(int i=0;i<n;i++)dp[r][i]=0;
    for(int t=0;t<(1<<n);t++) {
      for(int i=0;i<n;i++) {
        if(dp[t][i]==1<<29) continue;
        string e="";
        for(int j=0; j<n;j++) {
          if(t&(1<<j)) e+='1';
          else e+='0';
        }
        for(int j=0;j<n;j++) {
          if(t&(1<<j)) continue;
          for(int k=j+1;k<n;k++) {
            if(t&(1<<k)||s[j]==s[k]) continue;
            dp[t|(1<<j)|(1<<k)][j]=min(dp[t|(1<<j)|(1<<k)][j],dp[t][i]+abs(i-k)+abs(k-j));
            dp[t|(1<<j)|(1<<k)][k]=min(dp[t|(1<<j)|(1<<k)][k],dp[t][i]+abs(i-j)+abs(j-k));
          }
        }
      }
    }
    int ans=1<<29;
    for(int i=0;i<n;i++)ans=min(ans,dp[(1<<n)-1][i]);
    cout << ans << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 7268
final_rank: 4

code_snippet: #include<iostream>
#include<queue>
#include<string>
#include<cmath>
using namespace std;
int n, s, t; int dp[16][65536], p[16][16];
queue<pair<int, int>>Q;
int main() {
	while (true) {
		cin >> n; s = 0; t = 0; if (n == 0)break;
		for (int i = 0; i < n; i++) { for (int j = 0; j < (1 << n); j++)dp[i][j] = 999999999; }
		string S1; cin >> S1; for (int i = 0; i < S1.size(); i++) { if (S1[i] == 'B')s += (1 << i); }
		string S2; cin >> S2; for (int i = 0; i < S2.size(); i++) { if (S2[i] == 'B')t += (1 << i); }
		for (int i = 0; i < n; i++) { dp[i][s] = 0; Q.push(make_pair(i, s)); }
		while (!Q.empty()) {
			int a1 = Q.front().first, a2 = Q.front().second; Q.pop();
			if (a1 < n - 1 && dp[a1 + 1][a2] > dp[a1][a2] + 1) { dp[a1 + 1][a2] = dp[a1][a2] + 1; Q.push(make_pair(a1 + 1, a2)); }
			if (a1 >= 1 && dp[a1 - 1][a2] > dp[a1][a2] + 1) { dp[a1 - 1][a2] = dp[a1][a2] + 1; Q.push(make_pair(a1 - 1, a2)); }
			for (int i = 0; i < n; i++) {
				int bit[20]; for (int j = 0; j < n; j++)bit[j] = (a2 / (1 << j)) % 2;
				swap(bit[i], bit[a1]); int cost = abs(i - a1);
				int ret = 0; for (int j = 0; j < n; j++)ret += (1 << j)*bit[j];
				if (dp[i][ret] > dp[a1][a2] + cost) { dp[i][ret] = dp[a1][a2] + cost; Q.push(make_pair(i, ret)); }
			}
		}
		int minx = 999999999; for (int i = 0; i < n; i++)minx = min(minx, dp[i][t]);
		cout << minx << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 5410
memory_kb: 7584
final_rank: 16