题目 3180: 蓝桥杯2023年第十四届省赛真题-棋盘
题目描述
小蓝拥有 n × n 大小的棋盘,一开始棋盘上全都是白子。小蓝进行了 m 次操作,
每次操作会将棋盘上某个范围内的所有棋子的颜色取反 (也就是白色棋子变为黑色,黑色棋子变为白色)。
请输出所有操作做完后棋盘上每个棋子的颜色。
解题思路
1、两重循环,时间复杂度是
O
(
n
2
)
O(n^2)
O(n2),优化一下输入输出,能过全部案例
代码
import java.io.*;
import java.util.*;
public class Main {
static int N = 2000 + 10;
static int[][] arr = new int[N][N];
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int next() throws IOException {
st.nextToken();
return (int) st.nval;
}
public static void main(String[] args) throws IOException {
int n = next();
int m = next();
// 棋子颜色,避免弄混了
int white = 0;
int black = 1;
// 行和列坐标
int x1, y1, x2, y2;
int t;
for (int i = 0; i < m; i++) {
x1 = next() - 1;
y1 = next() - 1;
x2 = next() - 1;
y2 = next() - 1;
for (int j = x1; j <= x2; j++) {
for (int k = y1; k <= y2; k++) {
t = arr[j][k];
t = (t == white) ? black : white;
arr[j][k] = t;
}
}
}
// 打印二维数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(arr[i][j]);
}
out.println();
out.flush();
}
}
}
2、使用二维拆分
import java.io.*;
import java.util.*;
public class Main {
static int N = 2000 + 10;
static int[][] a = new int[N][N];
static int[][] b = new int[N][N];
static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int next() throws IOException {
st.nextToken();
return (int) st.nval;
}
static void insert(int x1, int y1, int x2, int y2, int c) {
b[x1][y1] += c;
b[x1][y2 + 1] -= c;
b[x2 + 1][y1] -= c;
b[x2 + 1][y2 + 1] += c;
}
public static void main(String[] args) throws IOException {
int n = next();
int m = next();
// 行和列坐标
int x1, y1, x2, y2;
int t = 1;
while (m-- > 0) {
x1 = next();
y1 = next();
x2 = next();
y2 = next();
// 每次操作均对某一矩阵里面的数+1
insert(x1, y1, x2, y2, 1);
}
// 打印二维数组a
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
a[i][j] = a[i - 1][j] + a[i][j - 1] + a[i - 1][j - 1] + b[i][j];
// 如果这个位置的数是奇数表示这个位置和最初的颜色相反
// 如果这个位置的数是偶数,表示操作了偶数次,棋子颜色和原来没操作一样
if ((a[i][j] & 1) == 1) {
out.print(1);
} else {
out.print(0);
}
}
out.println();
out.flush();
}
}
}