-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathG.java
More file actions
114 lines (102 loc) · 3.4 KB
/
Copy pathG.java
File metadata and controls
114 lines (102 loc) · 3.4 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.io.IOException;
import java.io.InputStream;
public class G {
public static void main(String[] args) throws Exception {
FastScanner fs = new FastScanner(System.in);
Integer nObj = fs.nextIntNullable();
Integer mObj = fs.nextIntNullable();
if (nObj == null || mObj == null) {
System.out.println(-1);
return;
}
int n = nObj, m = mObj;
int[][] state = new int[n][m];
for (int i = 0; i < n; i++) {
String line = fs.nextTokenLineTrimmed();
while (line.length() < m) {
String extra = fs.nextTokenLineTrimmed();
line += extra;
}
for (int j = 0; j < m; j++) {
char c = line.charAt(j);
if (c == 'S') state[i][j] = 1;
else if (c == 'K') state[i][j] = 0;
else {
System.out.println(-1);
return;
}
}
}
int best = Integer.MAX_VALUE;
for (int r0 = 0; r0 <= 1; r0++) {
int[] R = new int[n];
int[] C = new int[m];
for (int j = 0; j < m; j++) {
C[j] = state[0][j] ^ r0;
}
for (int i = 0; i < n; i++) {
R[i] = state[i][0] ^ C[0];
}
boolean ok = true;
outer:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if ((R[i] ^ C[j]) != state[i][j]) {
ok = false;
break outer;
}
}
}
if (ok) {
int steps = 0;
for (int x : R) steps += x;
for (int x : C) steps += x;
best = Math.min(best, steps);
}
}
System.out.println(best == Integer.MAX_VALUE ? -1 : best);
}
static class FastScanner {
private final InputStream in;
private final byte[] buffer = new byte[1 << 16];
private int ptr = 0, len = 0;
FastScanner(InputStream is) { in = is; }
private int read() throws IOException {
if (ptr >= len) {
len = in.read(buffer);
ptr = 0;
if (len <= 0) return -1;
}
return buffer[ptr++];
}
Integer nextIntNullable() throws IOException {
int c;
do {
c = read();
if (c == -1) return null;
} while (c <= ' ');
int sgn = 1;
if (c == '-') { sgn = -1; c = read(); }
int val = 0;
while (c > ' ') {
val = val * 10 + (c - '0');
c = read();
}
return val * sgn;
}
String nextTokenLineTrimmed() throws IOException {
StringBuilder sb = new StringBuilder();
int c;
while (true) {
c = read();
if (c == -1 || c == '\n' || c == '\r') break;
if (c != ' ') sb.append((char) c);
}
if (c == '\r') {
int next = read();
if (next != '\n') ptr--;
}
return sb.toString().trim();
}
}
}