题目链接

矩形总面积

个人思路

根据题意,两个矩形如果存在重叠部分,只会是这三种其一。不过再仔细观察这些边的关系,容易得到以下计算重叠区域大小的方法。

// 其中变量含义见题面

ll width = max(0LL, min(x2, x4) - max(x1, x3));

ll height = max(0LL, min(y2, y4) - max(y1, y3));

那么,这道题的解法就是,计算两个矩形的面积再减去重复部分(如果有重复部分的话) 看完下方的代码,可能有人奇怪为什么没去判断 width 和 height的大小,的确我省去了这一个判断。这是因为,在一个平面内,如果两个矩形有重叠部分的话,计算公式只能是上面那段代码计算方法,不明白可以对照图形来看,而当他们之间的差值为负的,那么就被我的 max 语句定为0了,只要width 和 height的值有一个为0,那么在减去的时候,就会减去的就是0。

if(width > 0 && height > 0)

参考代码

Java

import java.util.Scanner;

// AC

public class Main {

static long x1, y1, x2, y2, x3, y3, x4, y4;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

// 左下

x1 = sc.nextLong();

y1 = sc.nextLong();

// 右上

x2 = sc.nextLong();

y2 = sc.nextLong();

// 左下

x3 = sc.nextLong();

y3 = sc.nextLong();

// 右上

x4 = sc.nextLong();

y4 = sc.nextLong();

long res = (x2 - x1) * (y2 - y1) + (x4 - x3) * (y4 - y3);

// 计算重复区域面积

long width = Math.max(0, Math.min(x2, x4) - Math.max(x1, x3));

long height = Math.max(0, Math.min(y2, y4) - Math.max(y1, y3));

res -= width * height;

System.out.println(res);

}

}

C/C++

#include

using namespace std;

typedef long long ll;

// AC

int main()

{

ll x1, y1, x2, y2, x3, y3, x4, y4;

cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;

ll res = (x2 - x1) * (y2 - y1) + (x4 -x3) * (y4 - y3);

ll width = max(0LL, min(x2, x4) - max(x1, x3));

ll height = max(0LL, min(y2, y4) - max(y1, y3));

res -= width * height;

cout << res;

return 0;

}

成都新地标+1!西部首个机器人公园,亮相新川
2018年俄罗斯世界杯32强各支球队大集锦(完整版)