/* -*- coding: utf-8 -*- * * 3807.cc: No.3807 Crossword Key with Cropping (Hard) - yukicoder */ #include #include using namespace std; /* constant */ const int MAX_H = 600; const int MAX_W = 600; const int BN = 4; const int BBITS = 1 << BN; const int L = 1, R = 2, U = 4, D = 8; /* typedef */ /* global variables */ char fs[MAX_H][MAX_W]; int msks[MAX_H][MAX_W]; int css[BBITS][MAX_H + 1][MAX_W + 1]; /* subroutines */ bool leftb(int y, int x) { return x == 0 || fs[y][x - 1] == '#'; } bool rightb(int y, int x, int w) { return x == w - 1 || fs[y][x + 1] == '#'; } bool upb(int y, int x) { return y == 0 || fs[y - 1][x] == '#'; } bool downb(int y, int x, int h) { return y == h - 1 || fs[y + 1][x] == '#'; } int gen_msk(int h, int w, int y, int x) { int msk = 0; if (leftb(y, x)) msk |= L; if (rightb(y, x, w)) msk |= R; if (upb(y, x)) msk |= U; if (downb(y, x, h)) msk |= D; return msk; } bool is_key(int h, int w, int y, int x, int bits) { return fs[y][x] == '.' && (((bits & L) && ! (bits & R)) || // horizental key ((bits & U) && ! (bits & D)) || // vertical key (bits == BBITS - 1)); // one key } int rect(int y0, int x0, int y1, int x1, int bits) { return css[bits][y1][x1] - css[bits][y1][x0] - css[bits][y0][x1] + css[bits][y0][x0]; } /* main */ int main() { int h, w; scanf("%d%d", &h, &w); for (int i = 0; i < h; i++) scanf("%s", fs[i]); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) msks[i][j] = gen_msk(h, w, i, j); for (int bits = 0; bits < BBITS; bits++) for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) css[bits][i + 1][j + 1] = (is_key(h, w, i, j, msks[i][j] | bits) ? 1 : 0) + css[bits][i + 1][j] + css[bits][i][j + 1] - css[bits][i][j]; int qn; scanf("%d", &qn); while (qn--) { int a, b, c, d; scanf("%d%d%d%d", &a, &b, &c, &d); a--, b--; int s = 0, dy = c - a, dx = d - b; if (dy == 1 && dx == 1) s = rect(a, b, c, d, L | R | U | D); else if (dy == 1) { s = rect(a, b, c, b + 1, L | U | D) + rect(a, b + 1, c, d - 1, U | D) + rect(a, d - 1, c, d, R | U | D); } else if (dx == 1) { s = rect(a, b, a + 1, d, L | R | U) + rect(a + 1, b, c - 1, d, L | R) + rect(c - 1, b, c, d, L | R | D); } else { // dy > 1 && dx > 1 s = rect(a, b, a + 1, b + 1, L | U) + rect(a, d - 1, a + 1, d, R | U) + rect(c - 1, b, c, b + 1, L | D) + rect(c - 1, d - 1, c, d, R | D) + rect(a + 1, b, c - 1, b + 1, L) + rect(a + 1, d - 1, c - 1, d, R) + rect(a, b + 1, a + 1, d - 1, U) + rect(c - 1, b + 1, c, d - 1, D) + rect(a + 1, b + 1, c - 1, d - 1, 0); } printf("%d\n", s); } return 0; }