题目描述
链接:https://www.nowcoder.com/questionTerminal/1183548cd48446b38da501e58d5944eb?toCommentId=6383925
来源:牛客网
二货小易有一个W*H的网格盒子,网格的行编号为0H-1,网格的列编号为0W-1。每个格子至多可以放一块蛋糕,任意两块蛋糕的欧几里得距离不能等于2。
对于两个格子坐标(x1,y1),(x2,y2)的欧几里得距离为:
( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) ) 的算术平方根
小易想知道最多可以放多少块蛋糕在网格盒子里。
输入描述:
每组数组包含网格长宽W,H,用空格分割.(1 ≤ W、H ≤ 1000)
输出描述:
输出一个最多可以放的蛋糕数
示例1
输入
3 2
输出
4
思路
我们可以发现规律如下:
想上图交替出现。
所以不妨我们用数组表示网格盒子,在可以放蛋糕的地方填充1,不能放蛋糕的地方填充0,最后对整个数组求和。
代码实现
import java.util.Arrays;
import java.util.Scanner;
/**
* @ Created with IntelliJ IDEA.
* @ClassName Test
* @Description ( (x1-x2) * (x1-x2) + (y1-y2) * (y1-y2) ) 的算术平方根 2
* @Author by
* @Date 2020/6/29 17:59
*/
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt()) {
int w = scanner.nextInt();
int h = scanner.nextInt();
int[][] array = new int[w][h];
int count =0;
int tmp = 0;
//两层for循环对二维数组填充,可以放蛋糕的填1,不能放蛋糕的填0
for (int i = 0; i < w; i++) {
//填充时,tmp控制每2次给count赋值0或者1,目的交换每一行是从1开始还是从0开始填。
if(tmp == 2){
count = 1;
tmp = 0;
}else {
count = 0;
}
tmp++;
for (int j = 0; j < h; j++) {
if (count == 0 ) {
array[i][j] = 1;
if (j+1 < h){
array[i][j+1] = 1;
j++;
}
count = 1;
} else {
array[i][j] = 0;
if (j+1 < h){
array[i][j+1] = 0;
j++;
}
count = 0;
}
}
}
int sum = 0;
//对数组求和
for (int i = 0; i <w ; i++) {
for (int j = 0; j < h; j++) {
sum = sum + array[i][j];
}
}
System.out.println(sum);
}
}
}
代码2
根据规律,只要数清楚,每个4行中, i或i+1行的蛋糕数为 (n / 4) * 2 + (n % 4 < 2 ? n % 4 : 2) i+2或i+3行的蛋糕数为 ((n - 2) /4) * 2 + ((n - 2) % 4 < 2 ? (n - 2) % 4 : 2) 然后算清楚一共有多少个完整的4行就行, 当然是共有m / 4 个。 唯一要注意的就是处理行数除4有余数的情况,把最后可能剩余的1~3 行加进去即可。
import java.util.*;
public class Test5{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt(), n = sc.nextInt();
int evenICount = (n / 4) * 2 + (n % 4 < 2 ? n % 4 : 2);
int oddICount = ((n - 2) / 4) * 2 + ((n - 2) % 4 < 2 ? (n - 2) % 4 : 2);
int ans = m / 4 * (evenICount + oddICount) * 2;
if(m % 4 > 0) ans += evenICount;
if(m % 4 > 1) ans += evenICount;
if(m % 4 > 2) ans += oddICount;
System.out.println(ans);
}
}