USACO The Castle

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
ID: wcr19961
PROG: castle
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 55;
const int dx[] = {0, -1, 0, 1};
const int dy[] = {-1, 0, 1, 0};
int a[maxn][maxn], n, m;
int p[maxn][maxn], num[maxn * maxn];
bool vis[maxn][maxn];

void dfs(int i, int j, int id) {
vis[i][j] = true;
p[i][j] = id;
for (int k = 0; k < 4; ++k) {
if ((a[i][j] & (1 << k)) == 0) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m && !vis[x][y]) {
dfs(x, y, id);
}
}
}
}

int main() {
freopen("castle.in", "r", stdin);
freopen("castle.out", "w", stdout);
scanf("%d%d", &m, &n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &a[i][j]);
}
}
int cnt = 0, Max = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (!vis[i][j]) {
dfs(i, j, ++cnt);
}
Max = max(Max, ++num[p[i][j]]);
}
}
printf("%d\n%d\n", cnt, Max);
int ansx = 0, ansy = 0;
char ch = 0;
for (int j = 0; j < m; ++j) {
for (int i = n - 1; i >= 0; --i) {
for (int k = 1; k <= 2; ++k) {
if (a[i][j] & (1 << k)) {
int x = i + dx[k], y = j + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m) {
if (p[i][j] != p[x][y]) {
int tmp = num[p[i][j]] + num[p[x][y]];
if (tmp > Max) {
ansx = i, ansy = j;
ch = k == 1 ? 'N' : 'E';
Max = tmp;
}
}
}
}
}
}
}
printf("%d\n%d %d %c\n", Max, ansx + 1, ansy + 1, ch);
return 0;
}