thongtrikhuvucquocsol
quoc14
c_cpp
a month ago
3.0 kB
3
Indexable
Never
caidat
#include <iostream> using namespace std; struct point { int x, y; }; int n; int a[200][200]; int copy_a[200][200]; int visit0[200][200]; int visitxq[200][200]; int visitvung[200][200]; int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, 1, -1}; int cur0, curxq; int x_next, y_next; int tanso[200]; point zero[200]; point xungquanh[200]; point tmp; void resetvisit(int sign) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (sign == 0) { visit0[i][j] = 0; } else if (sign == 1) { visitxq[i][j] = 0; tanso[i] = 0; } else { visitvung[i][j] = 0; } } } } bool inside(int x, int y) { if (x >= 1 && x <= n && y >= 1 && y <= n) { return true; } return false; } void dfs0(int x, int y) { visit0[x][y] = 1; tmp.x = x; tmp.y = y; zero[++cur0] = tmp; for (int i = 0; i < 4; i++) { x_next = x + dx[i]; y_next = y + dy[i]; if (inside(x_next, y_next)) { if (a[x_next][y_next] == 0) { if (visit0[x_next][y_next] == 0) { dfs0(x_next, y_next); } } else { tmp.x = x_next; tmp.y = y_next; xungquanh[++curxq] = tmp; } } } } void dfsxq(int x, int y) { visitxq[x][y] = 1; tanso[a[x][y]]++; for (int i = 0; i < 4; i++) { x_next = x + dx[i]; y_next = y + dy[i]; if (inside(x_next, y_next)) { if (visitxq[x_next][y_next] == 0 && a[x_next][y_next] == a[x][y]) { dfsxq(x_next, y_next); } } } } void dfsvung(int x, int y) { visitvung[x][y] = 1; for (int i = 0; i < 4; i++) { x_next = x + dx[i]; y_next = y + dy[i]; if (inside(x_next, y_next)) { if (visitvung[x_next][y_next] == 0 && copy_a[x_next][y_next] == copy_a[x][y]) { dfsvung(x_next, y_next); } } } } void solve(int testcase) { cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; copy_a[i][j] = a[i][j]; } } resetvisit(0); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (a[i][j] == 0 && visit0[i][j] == 0) { int max_tanso = -1; int max_vung = -1; cur0 = 0; curxq = 0; resetvisit(1); dfs0(i, j); for (int k = 1; k <= curxq; k++) { int x = xungquanh[k].x; int y = xungquanh[k].y; if (visitxq[x][y] == 0) { dfsxq(x, y); } } for (int k = 1; k <= 5; k++) { if (tanso[k] >= max_tanso) { max_vung = k; } } for (int k = 1; k <= cur0; k++) { int x = zero[k].x; int y = zero[k].y; copy_a[x][y] = max_vung; } } } } resetvisit(2); int ans = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (visitvung[i][j] == 0) { ans++; dfsvung(i, j); } } } cout << "Case #" << testcase << endl; cout << ans << endl; } int main() { int t; cin >> t; for (int i = 1; i <= t; i++) { solve(i); } return 0; }
Leave a Comment