模拟和分类
1.先分类成矩阵是否重叠,没有重叠时矩阵的面积直接用左右两个坐标计算出来,当矩阵有重叠时就要进行查找重叠的矩阵坐标的左下标和右下标,根据Math.max和math.min来模拟出重叠的矩阵坐标。同时在计算时要注意计算的值会比较大,所以用long的类型不会数值溢出。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x1=scanner.nextInt();
int y1=scanner.nextInt();
int x2=scanner.nextInt();
int y2=scanner.nextInt();
int x3=scanner.nextInt();
int y3=scanner.nextInt();
int x4=scanner.nextInt();
int y4=scanner.nextInt();
//没有矩阵重叠时
if(x2<x3||y2<y3){
long s1c=x2-x1;
long s1k=y2-y1;
long sum1=s1c*s1k;
long s2c=x4-x3;
long s2k=y4-y3;
long sum2=s2c*s2k;
System.out.println(sum1+sum2);
}else{ //当有矩阵重叠时
//计算R1和R2的面积
long s1c=x2-x1;
long s1k=y2-y1;
//R1的面积
long sum1=s1c*s1k;
long s2c=x4-x3;
long s2k=y4-y3;
//R2的面积
long sum2=s2c*s2k;
//先查找重复的矩阵的左下角和右下角的坐标
long zho_x1=Math.max(x1,x3);
long zho_x2=Math.min(x2,x4);
long zho_y1=Math.max(y1,y3);
long zho_y2=Math.min(y2,y4);
//在计算重复矩阵的面积。
long sum_zho=(zho_x2-zho_x1)*(zho_y2-zho_y1);
System.out.println(sum1+sum2-sum_zho);
}
}
}