bzoj 1102
思路:用dfs 会爆栈,巨坑,要用bfs。
#include<bits/stdc++.h> #define LL long long #define fi first #define se second #define mk make_pair #define pii pair<int,int> #define piii pair<int, pair<int,int> > using namespace std; const int N = 1000 + 10; const int M = 10 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-7; int n, ans1, ans2, s[N][N], mx[N][N], mn[N][N]; int dx[] = {1, -1, 0, 0, 1, 1, -1, -1}; int dy[] = {0, 0, 1, -1, 1, -1, 1, -1}; bool vis[N][N]; bool bfs1(int sx, int sy) { queue<pii> que; vis[sx][sy] = true; que.push(mk(sx, sy)); bool flag = true; while(!que.empty()) { pii u = que.front(), v; que.pop(); if(mx[u.fi][u.se] > s[u.fi][u.se]) { flag = false; } for(int i = 0; i < 8; i++) { v.fi = u.fi + dx[i]; v.se = u.se + dy[i]; if(v.fi < 1 || v.fi > n || v.se < 1 || v.se > n || vis[v.fi][v.se] || s[v.fi][v.se] != s[u.fi][u.se]) continue; vis[v.fi][v.se] = true; que.push(v); } } return flag; } bool bfs2(int sx, int sy) { queue<pii> que; vis[sx][sy] = true; que.push(mk(sx, sy)); bool flag = true; while(!que.empty()) { pii u = que.front(), v; que.pop(); if(mn[u.fi][u.se] < s[u.fi][u.se]) { flag = false; } for(int i = 0; i < 8; i++) { v.fi = u.fi + dx[i]; v.se = u.se + dy[i]; if(v.fi < 1 || v.fi > n || v.se < 1 || v.se > n || vis[v.fi][v.se] || s[v.fi][v.se] != s[u.fi][u.se]) continue; vis[v.fi][v.se] = true; que.push(v); } } return flag; } int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { scanf("%d", &s[i][j]); mx[i][j] = mn[i][j] = s[i][j]; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { for(int k = 0; k < 8; k++) { int x = i + dx[k]; int y = j + dy[k]; if(x < 1 || x > n || y < 1 || y > n) continue; mx[i][j] = max(mx[i][j], s[x][y]); mn[i][j] = min(mn[i][j], s[x][y]); } } } ans1 = 0, ans2 = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(!vis[i][j]) { ans1 += bfs1(i, j); } } } memset(vis, false, sizeof(vis)); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(!vis[i][j]) { ans2 += bfs2(i, j); } } } printf("%d %d\n", ans1, ans2); return 0; }