矩形区域的交和并

矩形区域的交和并

时间: 1ms        内存:128M

描述:

    在编写图形界面软件的时候,经常会遇到处理两个矩形的关系。

    如图【1.jpg】所示,矩形的交集指的是:两个矩形重叠区的矩形,当然也可能不存在(参看【2.jpg】)。两个矩形的并集指的是:能包含这两个矩形的最小矩形,它一定是存在的。

    本题目的要求就是:由用户输入两个矩形的坐标,程序输出它们的交集和并集矩形。

    矩形坐标的输入格式是输入两个对角点坐标,注意,不保证是哪个对角,也不保证顺序(你可以体会一下,在桌面上拖动鼠标拉矩形,4个方向都可以的)。

输入:

    输入数据格式:
x1,y1,x2,y2
x1,y1,x2,y2
   
    数据共两行,每行表示一个矩形。每行是两个点的坐标。x坐标在左,y坐标在右。坐标系统是:屏幕左上角为(0,0),x坐标水平向右增大;y坐标垂直向下增大。

输出:

    要求程序输出格式:
x1,y1,长度,高度
x1,y1,长度,高度

    也是两行数据,分别表示交集和并集。如果交集不存在,则输出“不存在”

    前边两项是左上角的坐标。后边是矩形的长度和高度。

示例输入:

100,220,300,100	
150,150,300,300

示例输出:

150,150,150,70
100,100,200,200

提示:

参考答案(内存最优[1504]):

#include <iostream>
using namespace std;
int main()
{	
	char d;
	int x1,y1,x2,y2;
	int X1,Y1,X2,Y2;
	cin>>x1>>d>>y1>>d>>x2>>d>>y2;
	cin>>X1>>d>>Y1>>d>>X2>>d>>Y2;
	int bigx,smallx,bigy,smally;
	int bigX,smallX,bigY,smallY;
	if(x1>x2)
	{
		bigx=x1;
		smallx=x2;
	}
	else
	{
		bigx=x2;
		smallx=x1;
	}

	if(y1>y2)
	{
		bigy=y1;
		smally=y2;
	}
	else
	{
		bigy=y2;
		smally=y1;
	}

	if(X1>X2)
	{
		bigX=X1;
		smallX=X2;
	}
	else
	{
		bigX=X2;
		smallX=X1;
	}

	if(Y1>Y2)
	{
		bigY=Y1;
		smallY=Y2;
	}
	else
	{
		bigY=Y2;
		smallY=Y1;
	}
	int countx1,county1;  //small
	int countx2,county2;  
	countx1=smallx>smallX?smallx:smallX;
	county1=smally>smallY?smally:smallY;
	countx2=bigx>bigX?bigX:bigx;
	county2=bigy>bigY?bigY:bigy;
	if(countx1>0&&county1>0&&countx2-countx1>0&&county2-county1>0)
	cout<<countx1<<','<<county1<<','<<countx2-countx1<<','<<county2-county1<<endl;
	else cout<<"不存在"<<endl;
	countx1=smallx>smallX?smallX:smallx;
	county1=smally>smallY?smallY:smally;
	countx2=bigx>bigX?bigx:bigX;
	county2=bigy>bigY?bigy:bigY;
	cout<<countx1<<','<<county1<<','<<countx2-countx1<<','<<county2-county1<<endl;
	return 0;
}

参考答案(时间最优[0]):

#include <iostream>
using namespace std;
int main()
{	
	char d;
	int x1,y1,x2,y2;
	int X1,Y1,X2,Y2;
	cin>>x1>>d>>y1>>d>>x2>>d>>y2;
	cin>>X1>>d>>Y1>>d>>X2>>d>>Y2;
	int bigx,smallx,bigy,smally;
	int bigX,smallX,bigY,smallY;
	if(x1>x2)
	{
		bigx=x1;
		smallx=x2;
	}
	else
	{
		bigx=x2;
		smallx=x1;
	}

	if(y1>y2)
	{
		bigy=y1;
		smally=y2;
	}
	else
	{
		bigy=y2;
		smally=y1;
	}

	if(X1>X2)
	{
		bigX=X1;
		smallX=X2;
	}
	else
	{
		bigX=X2;
		smallX=X1;
	}

	if(Y1>Y2)
	{
		bigY=Y1;
		smallY=Y2;
	}
	else
	{
		bigY=Y2;
		smallY=Y1;
	}
	int countx1,county1;  //small
	int countx2,county2;  
	countx1=smallx>smallX?smallx:smallX;
	county1=smally>smallY?smally:smallY;
	countx2=bigx>bigX?bigX:bigx;
	county2=bigy>bigY?bigY:bigy;
	if(countx1>0&&county1>0&&countx2-countx1>0&&county2-county1>0)
	cout<<countx1<<','<<county1<<','<<countx2-countx1<<','<<county2-county1<<endl;
	else cout<<"不存在"<<endl;
	countx1=smallx>smallX?smallX:smallx;
	county1=smally>smallY?smallY:smally;
	countx2=bigx>bigX?bigx:bigX;
	county2=bigy>bigY?bigy:bigY;
	cout<<countx1<<','<<county1<<','<<countx2-countx1<<','<<county2-county1<<endl;
	return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注