【NOIP 2011】 Mayan遊戲
阿新 • • 發佈:2018-07-07
() tps maya mem 深度 may rem can remove
【題目鏈接】
https://www.luogu.org/problemnew/show/P1312
【算法】
深度優先搜索
【代碼】
#include<bits/stdc++.h> using namespace std; struct info { int x,y,op; } step[10]; int i,n,t,x; int a[10][10]; bool solved; inline void print() { int i; for (i = 1; i <= n; i++) printf("%d %d %d\n",step[i].x - 1,step[i].y - 1,step[i].op); } inline bool check() { int i; for (i = 1; i <= 5; i++) { if (a[i][1] != 0) return false; } return true; } inline bool Remove() { int i,j,x,y,t; boolret = false; bool d[10][10]; memset(d,false,sizeof(d)); for (i = 1; i <= 5; i++) { for (j = 1; j <= 7; j++) { if (a[i][j]) { for (x = j + 1; a[i][j] == a[i][x] && x <= 7; x++); if (x - j >= 3) { for (y = j; y < x; y++) d[i][y] = true; ret = true; } for (x = i + 1; a[i][j] == a[x][j] && x <= 5; x++); if (x - i >= 3) { for (y = i; y < x; y++) d[y][j] = true; ret = true; } } } } for (i = 1; i <= 5; i++) { for (j = 1; j <= 7; j++) { if (d[i][j]) a[i][j] = 0; } } for (i = 1; i <= 5; i++) { t = 0; for (j = 1; j <= 7; j++) { if (!a[i][j]) { for (x = j + 1; x <= 7 && !a[i][x]; x++); a[i][j] = a[i][x]; a[i][x] = 0; } } } return ret; } inline void dfs(int dep) { int i,j,x,y; int b[10][10]; if (dep > n) { if (check()) { solved = true; print(); } return; } for (i = 1; i <= 5; i++) { for (j = 1; j <= 7; j++) { b[i][j] = a[i][j]; } } for (i = 1; i <= 5; i++) { for (j = 1; j <= 7; j++) { if (i < 5 && a[i][j] != 0) { if (a[i+1][j] != 0) { step[dep] = (info){i,j,1}; swap(a[i][j],a[i+1][j]); while (Remove()); dfs(dep+1); if (solved) return; for (x = 1; x <= 5; x++) { for (y = 1; y <= 7; y++) { a[x][y] = b[x][y]; } } } else { step[dep] = (info){i,j,1}; for (x = j - 1; x >= 1 && !a[i+1][x]; x--); a[i+1][x+1] = a[i][j]; for (x = j; x <= 7; x++) a[i][x] = a[i][x+1]; while (Remove()); dfs(dep+1); if (solved) return; for (x = 1; x <= 5; x++) { for (y = 1; y <= 7; y++) { a[x][y] = b[x][y]; } } } } if (i > 1 && a[i][j] != 0) { if (a[i-1][j] == 0) { step[dep] = (info){i,j,-1}; for (x = j - 1; x >= 1 && !a[i-1][x]; x--); a[i-1][x+1] = a[i][j]; for (x = j; x <= 7; x++) a[i][x] = a[i][x+1]; while (Remove()); dfs(dep+1); if (solved) return; for (x = 1; x <= 5; x++) { for (y = 1; y <= 7; y++) { a[x][y] = b[x][y]; } } } } } } } int main() { scanf("%d",&n); for (i = 1; i <= 5; i++) { t = 0; while (scanf("%d",&x) && x) a[i][++t] = x; } solved = false; dfs(1); if (!solved) printf("-1\n"); return 0; }
【NOIP 2011】 Mayan遊戲