华为OD机试 - 矩形相交的面积(Java)

题目描述

给出3组点坐标(x, y, w, h),-1000<x,y<1000,w,h为正整数。
(x, y, w, h)表示平面直角坐标系中的一个矩形:
x, y为矩形左上角坐标点,w, h向右w,向下h。
(x, y, w, h)表示x轴(x, x+w)和y轴(y, y-h)围成的矩形区域;
(0, 0, 2, 2)表示 x轴(0, 2)和y 轴(0, -2)围成的矩形区域;
(3, 5, 4, 6)表示x轴(3, 7)和y轴(5, -1)围成的矩形区域;
求3组坐标构成的矩形区域重合部分的面积。

输入描述

3行输入分别为3个矩形的位置,分别代表“左上角x坐标”,“左上角y坐标”,“矩形宽”,“矩形高” -1000 <= x,y < 1000

输出描述

输出3个矩形相交的面积,不相交的输出0。

用例

输入1 6 4 4
3 5 3 4
0 3 7 3
输出2
说明

 

输入100 1
1
0 90 200
输出-1
说明组成设备需要1个元件,但是元件价格大于预算,因此无法组成设备,返回-1

 题目解析:

为图加上坐标

如上图所示,交叉区域的

长:Math.min(x1+w1, x2+w2, x3+w3) - Math.max(x1, x2, x3)

宽:Math.min(y1, y2, y3) - Math.max(y1-h1, y2-h2, y3-h3)

如果长度 <=0 或者 宽度<=0,则三个矩形不存在交叉区域,返回0

Java

import java.util.Scanner;
 
public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
 
    int x1 = sc.nextInt();
    int y1 = sc.nextInt();
    int w1 = sc.nextInt();
    int h1 = sc.nextInt();
 
    int x2 = sc.nextInt();
    int y2 = sc.nextInt();
    int w2 = sc.nextInt();
    int h2 = sc.nextInt();
 
    int x3 = sc.nextInt();
    int y3 = sc.nextInt();
    int w3 = sc.nextInt();
    int h3 = sc.nextInt();
 
    int wid = getMin(x1 + w1, x2 + w2, x3 + w3) - getMax(x1, x2, x3);
    if (wid <= 0) {
      System.out.println(0);
      return;
    }
 
    int hei = getMin(y1, y2, y3) - getMax(y1 - h1, y2 - h2, y3 - h3);
    if (hei <= 0) {
      System.out.println(0);
      return;
    }
 
    System.out.println(wid * hei);
  }
 
  public static int getMax(int n1, int n2, int n3) {
    int max = Math.max(n1, n2);
    max = Math.max(max, n3);
    return max;
  }
 
  public static int getMin(int n1, int n2, int n3) {
    int min = Math.min(n1, n2);
    min = Math.min(min, n3);
    return min;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清水乐园

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值