// yukicoder: No.228 ゆきこちゃんの15パズル // 2019.7.5 bal4u #include #include typedef unsigned long long ull; #if 1 #define gc() getchar_unlocked() #else #define gc() getchar() #endif int in() { // 非負整数の入力 int n = 0, c = gc(); do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0'); return n; } #define HASHSIZ 2000081 ull hash[HASHSIZ+5], *hashend = hash + HASHSIZ; int insert(char a[4][4]) { int r, c; ull s, *p; s = 0; for (r = 0; r < 4; r++) for (c = 0; c < 4; c++) { s <<= 4, s |= a[r][c]; } p = hash + (int)(s % HASHSIZ); while (*p) { if (*p == s) return 0; if (++p == hashend) p = hash; } *p = s; return 1; } typedef struct { char a[4][4], r, c; int b; } Q; Q q[1000000]; int top; char s[4][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}}; int mv[4][2] = {{-1,0},{0,1},{1,0},{0,-1}}; void swap(char b[4][4], char a[4][4], int nr, int nc, int r, int c) { int t; memcpy(b, a, 16); t = b[r][c], b[r][c] = b[nr][nc], b[nr][nc] = t; } int main() { int i, b, t, r, c, rr, cc; char a[4][4], aa[4][4]; for (r = 0; r < 4; r++) for (c = 0; c < 4; c++) { q[0].a[r][c] = t = in(); if (t == 0) q[0].r = r, q[0].c = c; } top = 1; while (top) { r = q[--top].r, c = q[top].c, memcpy(a, q[top].a, 16), b = q[top].b; if (memcmp(a, s, 16) == 0) { puts("Yes"); return 0; } if (!insert(a)) continue; for (i = 0; i < 4; i++) { rr = r + mv[i][0], cc = c + mv[i][1]; if (rr < 0 || rr >= 4 || cc < 0 || cc >= 4) continue; if ((b >> a[rr][cc]) & 1) continue; swap(aa, a, rr, cc, r, c); q[top].r = rr, q[top].c = cc, memcpy(q[top].a, aa, 16), q[top++].b = b | (1 << a[rr][cc]); } } puts("No"); return 0; }