真的觉得好沧桑~(╯‵□′)╯︵┻━┻
什么辣鸡玩意儿?当我快乐地打dfs时50分时,别人都用bfs愉快地A了。
放几个数据:
3
1 1 1
1 1 1
1 1 1
ans:1 1
4
1 1 1 3
1 1 3 3
1 1 3 3
1 1 3 3
我的lj算法在某些数被同类包围时会错,因为此时的tot0和tot1都是0。
改进一下就好了。拜拜~
#include<cstdio>
#include<cctype>
#include<iostream>
using namespace std;
const int N = 1002;
int Max, Min, ans1, ans0, n, G[N][N], dir[10][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}, vis[N][N];
void read(int &x) {
x = 0;
char s = getchar();
while(! isdigit(s))
s = getchar();
while(isdigit(s)) {
x = (x << 1) + (x << 3) + (s ^ 48);
s = getchar();
}
}
int getSta(const int x, const int y) {
int tot1 = 0, tot0 = 0;
for(int i = 0; i < 8; ++ i) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > n)
continue;
if(vis[tx][ty] == 2 && G[tx][ty] == G[x][y])
return -1;
if(G[tx][ty] > G[x][y])
++ tot0;
if(G[tx][ty] < G[x][y])
++ tot1;
}
if(tot0 && tot1)
return -1;
if(tot0)
return 0;
if(tot1)//之前写法:else return 1;
return 1;
return 2;
}
bool dfs(const int x, const int y, const int sta, const int cnt) {
int S = getSta(x, y);
bool flag = 0;
if(S == -1 || (sta != S && sta != -1 && S != 2)) {
vis[x][y] = 2;
return 0;
}
for(int i = 0; i < 8; ++ i) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > n || vis[tx][ty] || G[tx][ty] != G[x][y])
continue;
vis[tx][ty] = 1;
if(dfs(tx, ty, S, cnt + 1) == 0)
flag = 1;
}
if(flag) {
vis[x][y] = 2;
return 0;
}
return 1;
}
int main() {
int sta;
read(n);
Min = (1 << 30) - 1;
for(int i = 1; i <= n; ++ i)
for(int j = 1; j <= n; ++ j) {
read(G[i][j]);
Max = max(Max, G[i][j]);
Min = min(Min, G[i][j]);
}
if(Max == Min)
return ! printf("1 1\n");
for(int i = 1; i <= n; ++ i) {
for(int j = 1; j <= n; ++ j) {
if(vis[i][j])
continue;
if(dfs(i, j, -1, 1)) {
sta = getSta(i, j);
if(sta == 1)
++ ans1;
else
++ ans0;
}
}
}
printf("%d %d\n", ans1, ans0);
return 0;
}