【蓝桥备赛】矩形总面积——计算几何

题目链接

矩形总面积

个人思路

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

	// 其中变量含义见题面
	ll width = max(0LL, min(x2, x4) - max(x1, x3));
    ll height = max(0LL, min(y2, y4) - max(y1, y3));

那么,这道题的解法就是,计算两个矩形的面积再减去重复部分(如果有重复部分的话)
看完下方的代码,可能有人奇怪为什么没去判断 widthheight的大小,的确我省去了这一个判断。这是因为,在一个平面内,如果两个矩形有重叠部分的话,计算公式只能是上面那段代码计算方法,不明白可以对照图形来看,而当他们之间的差值为负的,那么就被我的 max 语句定为0了,只要widthheight的值有一个为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<bits/stdc++.h>
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;
}
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值