1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include <map> #include <cstdio> #define maxN 1010 std::map<int, std::map<int, int> > f[2]; int Ans = 0, n = 0, m = 0, q = 0; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int color[maxN][maxN], flag[maxN][maxN]; int queue[maxN * maxN][2], size[maxN * maxN]; int read () { int x = 0; char c = getchar(); while(c < '0' || c > '9') { c = getchar(); } while(c >= '0' && c <= '9') { x = x * 10 + (c - '0'); c = getchar(); } return x; } void bfs (int Sx, int Sy, int C) { int head = 1, tail = 2; queue[1][0] = Sx, queue[1][1] = Sy; while(head < tail) { int x = queue[head][0], y = queue[head][1]; for(register int k = 0;k <= 3; k++) { int nx = x + dx[k]; int ny = y + dy[k]; if(nx >= 1 && nx <= n && ny >= 1 && ny <= m) { if(color[nx][ny] == C) { Ans++; flag[nx][ny] = color[nx][ny] = 0; queue[tail][0] = nx, queue[tail][1] = ny; tail++; } else if(flag[nx][ny] == 1) { flag[nx][ny] = 2; int Now = ++size[color[nx][ny]]; f[0][color[nx][ny]][Now] = nx; f[1][color[nx][ny]][Now] = ny; } } } head++; } } int main () { scanf("%d %d %d %*d", &n, &m, &q); for(register int i = 1;i <= n; i++) { for(register int j = 1;j <= m; j++) { flag[i][j] = 1; color[i][j] = read(); } } Ans = 1; int Now = color[1][1]; flag[1][1] = color[1][1] = 0; bfs(1, 1, Now); while(q--) { int Color = read(); for(register int i = 1;i <= size[Color]; i++) { int x = f[0][Color][i], y = f[1][Color][i]; if(flag[x][y] == 2) { Ans++; Now = color[x][y]; flag[x][y] = color[x][y] = 0; bfs(x, y, Now); } } size[Color] = 0; f[0][Color].clear(), f[1][Color].clear(); printf("%d\n", Ans); } return 0; }
|