牛客网 矩形重叠 java

题目描述

平面内有n个矩形, 第i个矩形的左下角坐标为(x1[i], y1[i]), 右上角坐标为(x2[i], y2[i])。
如果两个或者多个矩形有公共区域则认为它们是相互重叠的(不考虑边界和角落)。
请你计算出平面内重叠矩形数量最多的地方,有多少个矩形相互重叠。

输入描述:

输入包括五行。
第一行包括一个整数n(2 <= n <= 50), 表示矩形的个数。
第二行包括n个整数x1[i](-10^9 <= x1[i] <= 10^9),表示左下角的横坐标。
第三行包括n个整数y1[i](-10^9 <= y1[i] <= 10^9),表示左下角的纵坐标。
第四行包括n个整数x2[i](-10^9 <= x2[i] <= 10^9),表示右上角的横坐标。
第五行包括n个整数y2[i](-10^9 <= y2[i] <= 10^9),表示右上角的纵坐标。
输出描述:
输出一个正整数, 表示最多的地方有多少个矩形相互重叠,如果矩形都不互相重叠,输出1。

示例1

输入
2
0 90
0 90
100 200
100 200
输出
2

解题思路:

对于每个矩形是否重叠,获取重叠的矩形放回Arraylist,继续循环


import java.util.*;

public class Main {
	public static class rect{
		public long x1,x2,y1,y2;
		public int overlap;
		public rect(long a1,long b1,long a2,long b2 , int o){
		 x1=a1;
		 y1=b1;
		 x2=a2;
		 y2=b2;
		 overlap =o;
		}
		public rect(long a1,long b1,long a2,long b2){
			 x1=a1;
			 y1=b1;
			 x2=a2;
			 y2=b2;
			 overlap =1;
			}
	}
	public static boolean isOverlap(rect i,rect s) {
		if (i.x2<=s.x1 || i.x1>=s.x2 || i.y1>=s.y2 || i.y2<=s.y1)
			return false;
		return true;
	}
	
	public static rect getOverlap(rect i,rect s) {
		long x1 = Math.max(i.x1, s.x1);
		long x2 = Math.min(i.x2, s.x2);
		long y1 = Math.max(i.y1, s.y1);
		long y2 =Math.min(i.y2, s.y2);
		return new rect(x1,y1,x2,y2);
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int max_overlap = 1;
		ArrayList<Long> x1 =new ArrayList<Long>();
		ArrayList<Long> x2 =new ArrayList<Long>();
		ArrayList<Long> y1 =new ArrayList<Long>();
		ArrayList<Long> y2 =new ArrayList<Long>();
		ArrayList<rect> rects = new ArrayList<rect>();
		for (int i=0;i<n;++i) {
			Long tem1 = in.nextLong();
			x1.add(tem1);
		}
		for (int i=0;i<n;++i) {
			Long tem2 = in.nextLong();
			y1.add(tem2);
		}
		for (int i=0;i<n;++i) {
			Long tem3 = in.nextLong();
			x2.add(tem3);
		}
		for (int i=0;i<n;++i) {
			Long tem4 = in.nextLong();
			y2.add(tem4);
		}
		for (int i=0;i<n;++i) {
			rect tem = new rect(x1.get(i), y1.get(i), x2.get(i), y2.get(i));
			int size = rects.size();
			for (int k=0;k<size;++k) {
				if (isOverlap(tem, rects.get(k))) {
					rect tem2 = getOverlap(tem, rects.get(k));
					tem2.overlap = rects.get(k).overlap+1;
					if (tem2.overlap>max_overlap) {
						max_overlap = tem2.overlap;
					}
					rects.add(tem2);
				}
			}
            rects.add(tem);
		}
		System.out.println(max_overlap);
		//
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值