2137. 【GDKOI2004】城市统计 (Standard IO)
Time Limits: 1000 ms Memory Limits: 128000 KB Detailed Limits
Goto ProblemSet做法:先用bfs求出每个点的权值,然后跑一遍二位前缀和就好啦。
代码如下:
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <string> 5 #include <cstdlib> 6 #include <algorithm> 7 #define N 157 8 using namespace std; 9 int dis[N][N], dist[N][N], n, r, T, list[N * N][2], map[N][N]; 10 bool v[N][N]; 11 int dx[4] = {0, 1, 0, -1}; 12 int dy[4] = {1, 0, -1, 0}; 13 14 inline int max(int a, int b) { return a > b ? a : b; } 15 inline int min(int a, int b) { return a < b ? a : b; } 16 17 void readln() 18 { 19 for (int i = 1; i <= n; i++) 20 for (int j = 1; j <= n; j++) 21 scanf("%d", &map[i][j]); 22 } 23 24 inline bool check(int x, int y) 25 { 26 if (x >= 1 && y >= 1 && x <= n && y <= n && !v[x][y]) return 1; 27 return 0; 28 } 29 30 inline int abs(int x) { if (x < 0) return -x;} 31 32 inline int bfs(int x, int y) 33 { 34 int head = 0, tail = 0; 35 list[++tail][0] = x, list[tail][1] = y; 36 while (head <= tail) 37 { 38 head++; 39 int q = list[head][0], p = list[head][1]; 40 for (int i = 0; i <= 3; i++) 41 if (check(q + dx[i], p + dy[i])) 42 { 43 v[q + dx[i]][p + dy[i]] = 1; 44 if (map[q + dx[i]][p + dy[i]]) 45 { 46 for (int j = 1; j <= tail; j++) 47 v[list[j][0]][list[j][1]] = 0; 48 v[q + dx[i]][p + dy[i]] = 0; 49 return abs(q + dx[i] - x) + abs(p + dy[i] - y); 50 } 51 list[++tail][0] = q + dx[i]; 52 list[tail][1] = p + dy[i]; 53 } 54 } 55 } 56 57 void xgm() 58 { 59 for (int i = 1; i <= n; i++) 60 for (int j = 1; j <= n; j++) 61 dist[i][j] = dist[i - 1][j] + dist[i][j - 1] - dist[i - 1][j - 1] + dis[i][j]; 62 } 63 64 void writeln() 65 { 66 for (int i = 1; i <= n; i++) 67 { 68 for (int j = 1; j <= n - 1; j++) 69 printf("%d ", dist[min(i + r, n)][min(j + r, n)] - dist[min(i + r, n)][max(j - r - 1, 0)] - dist[max(i - r - 1, 0)][min(j + r, n)] + dist[max(i - r - 1, 0)][max(j - r - 1, 0)]); 70 printf("%d\n", dist[min(i + r, n)][min(n + r, n)] - dist[min(i + r, n)][max(n - r - 1, 0)] - dist[max(i - r - 1, 0)][min(n + r, n)] + dist[max(i - r - 1, 0)][max(n - r - 1, 0)]); 71 } 72 } 73 74 void work() 75 { 76 for (int i = 1; i <= n; i++) 77 for (int j = 1; j <= n; j++) 78 if (!map[i][j]) dis[i][j] = bfs(i, j); 79 xgm(); 80 writeln(); 81 } 82 83 int main() 84 { 85 scanf("%d", &T); 86 while (T--) 87 { 88 memset(dis, 0, sizeof(dis)); 89 memset(dist, 0, sizeof(dist)); 90 memset(map, 0, sizeof(map)); 91 scanf("%d%d", &n, &r); 92 readln(); 93 work(); 94 if (T != 0) printf("\n"); 95 } 96 }