HDU_2258
本来是Step里面遇到了HDU_2259的,结果发现要先做这个题……模拟题目中所说的规则就可以了。
#include<stdio.h> #include<string.h> #include<algorithm> #define MAXN 25 #define MAXD 410 int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}, L; int N, M, a[MAXN][MAXN]; struct List { int x, y; }list[MAXD]; void init() { int i, j; char b[MAXN]; for(i = N - 1; i >= 0; i --) { scanf("%s", b); for(j = 0; j < M; j ++) a[i][j] = b[j] - '0'; } } struct St { int N, M, g[MAXN][MAXN], cnt[MAXD], col[MAXN][MAXN]; void init(int N, int M, int g[][MAXN]) { this->N = N, this->M = M; memcpy(this->g, g, sizeof(this->g)); } inline int inside(int x, int y) { return x >= 0 && x < N && y >= 0 && y < M; } void color(int x, int y, int &cnt, int c) { int i, nx, ny; col[x][y] = c, ++ cnt; for(i = 0; i < 4; i ++) { nx = x + dx[i], ny = y + dy[i]; if(inside(nx, ny) && g[nx][ny] == g[x][y] && !col[nx][ny]) color(nx, ny, cnt, c); } } void erase(int x, int y) { int i, nx, ny; g[x][y] = 0; for(i = 0; i < 4; i ++) { nx = x + dx[i], ny = y + dy[i]; if(inside(nx, ny) && col[x][y] == col[nx][ny] && g[nx][ny]) erase(nx, ny); } } inline int find(int j) { for(int i = 0; i < N; i ++) if(g[i][j]) return 0; return 1; } void arrange() { int i, j, k, kmax; kmax = 0; for(j = 0; j < M; j ++) { k = 0; for(i = 0; i < N; i ++) if(g[i][j]) { if(i != k) g[k][j] = g[i][j], g[i][j] = 0; ++ k; } kmax = std::max(kmax, k); } N = kmax; k = 0; for(j = 0; j < M; j ++) if(!find(j)) { if(j != k) for(i = 0; i < N; i ++) g[i][k] = g[i][j]; ++ k; } M = k; } int gogo() { int i, j, ans = 0, max, x, y, c; for(;;) { max = c = 0; for(i = 0; i < N; i ++) for(j = 0; j < M; j ++) col[i][j] = 0; for(i = N - 1; i >= 0; i --) for(j = 0; j < M; j ++) if(g[i][j] && !col[i][j]) { ++ c, cnt[c] = 0; color(i, j, cnt[c], c); if(cnt[c] > max) max = cnt[c], x = i, y = j; } if(max <= 1) break; ans += (max - 1) * max; erase(x, y), arrange(); } return ans; } }; void solve() { St st; st.init(N, M, a); printf("%d\n", st.gogo()); } int main() { while(scanf("%d%d", &N, &M) == 2) { init(); solve(); } return 0; } /* Sample Input: 5 5 32345 32345 32345 32345 12111 5 5 32223 32213 32223 32221 12111 Sample Output: 112 204 */