思想
求两个矩形的交和并。
代码
import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;
public class Main{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args)throws IOException{
String[] input = in.readLine().split(",");
Rectangle R1 = new Rectangle(Integer.parseInt(input[0]), Integer.parseInt(input[1]), Integer.parseInt(input[2]), Integer.parseInt(input[3]));
R1.normalize();
input = in.readLine().split(",");
Rectangle R2 = new Rectangle(Integer.parseInt(input[0]), Integer.parseInt(input[1]), Integer.parseInt(input[2]), Integer.parseInt(input[3]));
R2.normalize();
if(R1.intersects(R2)) out.println(R1.intersection(R2));
else out.println("NO");
out.println(R1.union(R2));
out.flush();
out.close();
}
}
class Rectangle{
int x1, y1, x2, y2, h, w;
public Rectangle(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.h = x2-x1;
this.w = y2-y1;
}
public void normalize(){
if(this.x1>this.x2){int tmp = this.x1; this.x1 = this.x2; this.x2 = tmp;}
if(this.y1>this.y2){int tmp = this.y1; this.y1 = this.y2; this.y2 = tmp;}
}
//判断是否有矩形相交
public boolean intersects(Rectangle R2){
if(this.x2<R2.x1 || this.x1>R2.x2 || this.y2<R2.y1 || this.y1>R2.y2) return false;
else return true;
}
//获取两个矩形的交集
public Rectangle intersection(Rectangle R2){
return new Rectangle(Math.max(this.x1, R2.x1), Math.max(this.y1, R2.y1), Math.min(this.x2, R2.x2), Math.min(this.y2, R2.y2));
}
//获取两个矩形的并集
public Rectangle union(Rectangle R2){
return new Rectangle(Math.min(this.x1, R2.x1), Math.min(this.y1, R2.y1), Math.max(this.x2, R2.x2), Math.max(this.y2, R2.y2));
}
@Override
public String toString() {
return this.x1 +
"," + this.y1 +
"," + this.h +
"," + this.w;
}
}