杭电2056:
Rectangles

1 #include<iostream> 2 #include<iomanip> 3 using namespace std; 4 5 class p 6 { 7 public: 8 double x; 9 double y; 10 friend istream& operator >>(istream& in, p& x); 11 }; 12 13 istream& operator >>(istream& in, p& a) 14 { 15 in >> a.x >> a.y; 16 return in; 17 } 18 void swap(p& a, p& b) 19 { 20 if(a.x > b.x) 21 { 22 double t = a.x; 23 a.x = b.x; 24 b.x = t; 25 } 26 if(a.y > b.y) 27 { 28 double t = a.y; 29 a.y = b.y; 30 b.y = t; 31 } 32 } 33 int main() 34 { 35 p a, b, c, d; 36 while(cin >> a >> b >> c >> d) 37 { 38 swap(a, b); 39 swap(c, d); 40 double area = 0.00; 41 p m, n; 42 m.x = a.x > c.x ? a.x : c.x; 43 m.y = a.y > c.y ? a.y : c.y; 44 n.x = b.x > d.x ? d.x : b.x; 45 n.y = b.y > d.y ? d.y : b.y; 46 cout.setf(ios::fixed); 47 cout.precision(2); 48 area = (m.x > n.x || m.y > n.y) ? 0 : (n.x-m.x)*(n.y-m.y); 49 cout << area << endl; 50 } 51 return 0; 52 }
作图分析可知若两矩形相交相交两交点坐标应该是上述代码中的(x1,y1) (x2,y2),并且满足x2>x1 y2>y1,反之则两矩形不想交面积为0

1 #include<iostream> 2 #include<cmath> 3 #include<algorithm> 4 using namespace std; 5 int main() 6 { 7 double x1,y1,x2,y2,x3,y3,x4,y4; 8 double x[4],y[4]; 9 double s,w,h; 10 while(cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4) 11 { 12 x[0]=x1; 13 x[1]=x2; 14 x[2]=x3; 15 x[3]=x4; 16 y[0]=y1; 17 y[1]=y2; 18 y[2]=y3; 19 y[3]=y4; 20 sort(x,x+4); 21 sort(y,y+4); 22 w=fabs(x2-x1)+fabs(x4-x3)-(x[3]-x[0]); 23 h=fabs(y2-y1)+fabs(y4-y3)-(y[3]-y[0]); 24 s=w*h; 25 if(w<=0 || h<=0)s=0.00; 26 cout.setf(ios::fixed); 27 cout.precision(2); 28 cout << s << endl; 29 } 30 return 0; 31 }