[BASIC-18] 矩形面积交

来源:互联网 发布:限制网络流量的软件 编辑:程序博客网 时间:2024/05/05 23:18

基础练习 矩形面积交  
时间限制:1.0s   内存限制:512.0MB
问题描述
  平面上有两个矩形,它们的边平行于直角坐标系的X轴或Y轴。对于每个矩形,我们给出它的一对相对顶点的坐标,请你编程算出两个矩形的交的面积。
输入格式
  输入仅包含两行,每行描述一个矩形。
  在每行中,给出矩形的一对相对顶点的坐标,每个点的坐标都用两个绝对值不超过10^7的实数表示。
输出格式
  输出仅包含一个实数,为交的面积,保留到小数后两位。
样例输入
1 1 3 3
2 2 4 4
样例输出
1.00
分析:

1、需要注意的有:一个矩形有两对相对顶点,题目中没有具体说明给的是哪一对,所以都要考虑;输入数据中也没有说明相对顶点的输入顺序,这点也要注意到

2、针对 1 中注意事项,我们可以分情况讨论,也可以采取一种策略综合处理:比如说给出的一组坐标是 ( x1 ,y1 ) ( x2 ,y2 ) ,不管这组坐标的相对位置如何,我们都可以得到

主对角线上的相对顶点坐标 ( min ( x1 ,x2 ) ,max ( y1 ,y2 ) ) ( max ( x1 ,x2 ) ,min ( y1 ,y2 ) ) 或者是副对角线上的相对顶点坐标 ( min ( x1 ,x2 ) ,min ( y1 ,y2 ) ) ( max ( x1 ,x2 ) ,max ( y1 ,y2 ) ) ,这里我得到的是副对角线上的相对顶点坐标

3、假设我们通过 2 中综合处理的思想,已经得到副对角线上的相对顶点坐标 ( x1 ,y1 ) ( x2 ,y2 ) 和 ( a1 ,b1 ) ( a2 ,b2 ) 。注意!得到的坐标是有顺序的,( x1 ,y1 ) ( a1 ,b1 ) 始终是左下角,( x2 ,y2 ) ( a2 ,b2 ) 始终是右上角

4、通过 3 中得到的坐标,我们又可以得到矩形相交部分的坐标(暂时假设有相交的部分):( max ( x1 ,a1 ) ,max ( y1 ,b1 ) ) ( min ( x2 ,a2 ) ,min ( y2 ,b2 ) )。注意,这样得到的坐标也是有顺序的,( max ( x1 ,a1 ),max ( y1 ,b1 ) ) 是左下角,( min ( x2 ,a2 ),min ( y2 ,b2 ) ) 是右上角

5、判断矩形是否有相交的部分:利用 4 中得到的坐标数据,如果 max ( x1 ,a1 ) > min ( x2 ,a2 ) 或者 max ( y1 ,b1 ) > min ( y2 ,b2 ) ,就说明矩形之间没有相交的部分,反之则有

import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {double[] temp1 = new double[4];double[] temp2 = new double[4];double[] rect1 = new double[4];double[] rect2 = new double[4];for (int i = 0; i < 4; i++) {temp1[i] = scanner.nextDouble();}for (int i = 0; i < 4; i++) {temp2[i] = scanner.nextDouble();}// 得到第一个矩形的副对角线坐标rect1[0] = Math.min(temp1[0], temp1[2]);rect1[1] = Math.min(temp1[1], temp1[3]);rect1[2] = Math.max(temp1[0], temp1[2]);rect1[3] = Math.max(temp1[1], temp1[3]);// 得到第二个矩形的副对角线坐标rect2[0] = Math.min(temp2[0], temp2[2]);rect2[1] = Math.min(temp2[1], temp2[3]);rect2[2] = Math.max(temp2[0], temp2[2]);rect2[3] = Math.max(temp2[1], temp2[3]);// 得到矩形相交部分的坐标(副对角线)double[] rect = new double[4];rect[0] = Math.max(rect1[0], rect2[0]);rect[1] = Math.max(rect1[1], rect2[1]);rect[2] = Math.min(rect1[2], rect2[2]);rect[3] = Math.min(rect1[3], rect2[3]);double area = 0;if (rect[0] >= rect[2]) {System.out.printf("%.2f\r\n", area);} else {area = (rect[2] - rect[0]) * (rect[3] - rect[1]);System.out.printf("%.2f\r\n", area);}}}}
0 0
原创粉丝点击