Java
$\color{red}{— > 蓝桥杯辅导课题解}$
思路:
$根据题意,只有3种情况:$
$1、 全包含$
$2、 部分重叠$
$3、 无重叠$
$由此,先直接算下两矩形的面积,如果有重叠,减去重叠部分即可$
全包含:
部分重叠:
无重叠:
$时间复杂度:O(1)$
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long x1 = sc.nextLong(), y1 = sc.nextLong();
long x2 = sc.nextLong(), y2 = sc.nextLong();
long x3 = sc.nextLong(), y3 = sc.nextLong();
long x4 = sc.nextLong(), y4 = sc.nextLong();
long sum = 0, sum1 = 0;
sum = (x2 - x1) * (y2 - y1) + (x4 - x3) * (y4 - y3);
if (x3 < x2 && y3 < y2 && x4 > x1 && y4 > y1) { // 如果重叠,计算重叠部分
Long x_1 = Math.max(x1, x3);
Long y_1 = Math.max(y1, y3);
Long x_2 = Math.min(x2, x4);
Long y_2 = Math.min(y2, y4);
sum1 = (x_2 - x_1) * (y_2 - y_1);
}
System.out.println(sum - sum1);
}
}
确实挺不错
妙