算法每一题,成长每一天~
C0E47 矩形相交的面积
真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)
思路
Java
package com.ccr.paper_f;
import java.util.Scanner;
public class C0E47 {
/**
* 矩形
*/
static class Square {
int lbx; // left bottom x
int lby; // left bottom y
int rtx; // right top x
int rty; // right top y
/**
* 根据输入的值,构造矩形
*/
public Square(int ltx, int lty, int xPlus, int yDesc) {
this.lbx = ltx;
this.lby = lty - yDesc;
this.rtx = ltx + xPlus;
this.rty = lty;
}
public boolean isInside(double x, double y) {
return x >= lbx && x <= rtx && y >= lby && y <= rty;
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int xMin = Integer.MAX_VALUE;
int yMin = Integer.MAX_VALUE;
int xMax = Integer.MIN_VALUE;
int yMax = Integer.MIN_VALUE;
Square[] squares = new Square[3];
for (int i = 0; i < 3; i++) {
Square square = new Square(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt());
squares[i] = square;
xMin = Math.min(xMin, square.lbx);
yMin = Math.min(yMin, square.lby);
xMax = Math.max(xMax, square.rtx);
yMax = Math.max(yMax, square.rty);
}
// 遍历所有点,统计哪些点 同时在三个矩形内部,则为矩形相交
int count = 0;
for (int i = xMin; i < xMax; i++) {
for (int j = yMin; j < yMax; j++) {
boolean bothInside = true;
for (Square square : squares) {
if (!square.isInside(i + 0.5, j + 0.5)) {
bothInside = false;
break;
}
}
if (bothInside) {
count++;
}
}
}
System.out.println(count);
}
}
总结
~
算法要多练多练多练!!