http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2849 主要考优先级队列和一些剪枝技巧 #include <stdio.h> typedef struct { int x, y, ty, day; } HEAP_TYPE; int heap_size; /* Set your heap size */ HEAP_TYPE heap[250000 + 1]; /* heap array */ /* * if return 1 then a's priority is larger than b, * else return 0. */ int heap_compare (HEAP_TYPE a, HEAP_TYPE b) { if (a.day < b.day) return 1; if (a.day > b.day) return 0; if (a.ty < b.ty) return 1; else return 0; } #define PARENT(i) ((i)>>1) #define LEFT(i) ((i)<<1) #define RIGHT(i) (((i)<<1)+1) void heapify (int i) { int l, r, max, flag; HEAP_TYPE t; do { l = LEFT (i); r = RIGHT (i); max = i; flag = 0; if (l <= heap_size && heap_compare (heap[l], heap[max])) max = l; if (r <= heap_size && heap_compare (heap[r], heap[max])) max = r; if (max != i) { t = heap[i]; heap[i] = heap[max]; heap[max] = t; i = max; flag = 1; } } while (flag); } void build_max_heap () { int i; for (i = heap_size / 2; i > 0; i--) heapify (i); } HEAP_TYPE heap_extract_max () { HEAP_TYPE max = heap[1]; heap[1] = heap[heap_size]; --heap_size; heapify (1); return max; } void heap_increase_key (int i, HEAP_TYPE key) { int p; HEAP_TYPE t; heap[i] = key; while (i > 1 && heap_compare (heap[i], heap[p = PARENT (i)])) { t = heap[i]; heap[i] = heap[p]; heap[p] = t; i = p; } } void heap_insert (HEAP_TYPE key) { ++heap_size; heap_increase_key (heap_size, key); } int m, n, q, sum; int num[250001]; int map[500][500]; const int mov[4][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; #define MIN 0x80000000 void init () { int i, j; HEAP_TYPE p; heap_size = sum = 0; for (i = 1; i < 250001; i++) num[i] = 0; for (i = 0; i < m; i++) for (j = 0; j < n; j++) { scanf ("%d", &map[i][j]); if (map[i][j] > 0) { ++num[map[i][j]]; ++sum; p.x = i; p.y = j; p.ty = map[i][j]; p.day = 1; heap_insert (p); } } } int abs (int a) { return a < 0 ? -a : a; } void solve () { int i, flag; HEAP_TYPE p, t; while (heap_size) { p = heap_extract_max (); flag = MIN; for (i = 0; i < 4; i++) { t.x = p.x + mov[i][0]; t.y = p.y + mov[i][1]; if (t.x < 0 || t.x >= m || t.y < 0 || t.y >= n) continue; t.ty = p.ty; t.day = p.day; if (map[t.x][t.y] < 0) { if (t.day >= abs (map[t.x][t.y])) { map[t.x][t.y] = t.ty; ++num[t.ty]; ++sum; if (sum == m * n) return; heap_insert (t); } else { if (map[t.x][t.y] > flag) flag = map[t.x][t.y]; } } } if (flag != MIN) { p.day = -flag; heap_insert (p); } } } int main () { while (scanf ("%d%d", &m, &n) != EOF) { int t; init (); solve (); scanf ("%d", &q); while (q--) { scanf ("%d", &t); printf ("%d/n", num[t]); } } return 0; }