K皇后
K皇后
错误尝试思路:
1.一个一个点判断是否会被皇后攻击,会TLE,点太多
2.建立一张图,存皇后会攻击到的点,再把没有攻击到的点记录下来,可以解决TLE问题,但是会导致MLE,图太大
可尝试优化途径:对地图大小进行压缩
解法:
从图中可以看出皇后攻击的点有四个区域,同行同列,两斜边,并且斜边中的点可以通过点的行计算出列,因此可以压缩地图大小到一行

代码如下:(通过记录i值代替true值代表本行已被攻击的点,不用每次遍历另一行时需要初始化判断数组)
import java.util.*;
public class Main {
static int n,m,k;
/**
* 皇后坐标
*/
static int x[],y[];
/**
* 行
*/
static boolean row[];
/**
* 列
*/
static int column[];
static void read() {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
// 初始化皇后位置存储数组
x = new int[k];
y = new int[k];
// 初始化图(用一维存)
row = new boolean[n+1];
column = new int[m+1];
// 输入
for(int i=0;i<k;i++) {
// 皇后坐标
x[i] = in.nextInt(); y[i] = in.nextInt();
// 当前行有皇后
row[x[i]] = true;
}
}
static int cul() {
int result = 0;
int sum;
// 按行遍历
for(int i=1;i<=n;i++) {
// 当前行没有皇后
if(!row[i]) {
// 假设都没有被攻击
sum = m;
// 遍历皇后
for(int j=0;j < k;j++) {
// 竖直攻击
if(column[y[j]] != i) {
sum--;
column[y[j]] = i;
}
// 临时变量
int temp;
// 斜率为正那边攻击
temp = x[j] + y[j];
if(!yue(temp - i) && column[temp - i] != i) {
sum--;
column[temp-i] = i;
}
// 斜率为负那边攻击
temp = x[j] - y[j];
if(!yue(i - temp) && column[i - temp] != i) {
sum--;
column[i - temp] = i;
}
}
result += sum;
}
}
return result;
}
// 越界判断
static boolean yue(int y) {
if(y <= 0 || y > m) return true;
return false;
}
public static void main(String[] args) {
read();
System.out.println(cul());
}
}

浙公网安备 33010602011771号