互娱C++岗 秋招笔试题
第二题:
//求解重叠矩形的组合面积
#include<bits/stdc++.h>
using namespace std;
typedef struct Rect
{
int x1;
int y1;
int x2;
int y2;
// Rect(int x1, int y1, int x2, int y2):
// x1(x1), y1(y1), x2(x2), y2(y2) {}
} Rect;
bool isover(const Rect &r1, const Rect &r2)
{
if(r1.x2 > r2.x1 && r2.x2 > r1.x1 && r1.y2 > r2.y1 && r2.y2 > r1.y1) return true;
else
return false;
}
int main()
{
int T,n;
cin>>T;
while(T--)
{
cin>>n;
vector<Rect> a(n+2);
int ans = 0;
for(int i=0; i<n; i++)
{
cin>>a[i].x1>>a[i].y1>>a[i].x2>>a[i].y2;
//ans += (a[i].x2-a[i].x1)*(a[i].y2 - a[i].y1);
}
int area;
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(isover(a[i], a[j]) == true)
{
ans += (a[i].y2 - a[i].y1) * (a[i].x2 - a[i].x1);
ans += (a[j].y2 - a[j].y1) * (a[j].x2 - a[j].x1);
// cout<<ans<<endl;
//考虑两个矩形左下角坐标的大小和右上角坐标的大小
if(a[i].x1 >= a[j].x1 && a[i].y1 >= a[j].y1 && a[i].x2 >= a[j].x2 && a[i].y2 >= a[j].y2)
{
area = (a[j].y2-a[i].y1) * (a[j].x2 - a[i].x1);
ans -= area;
// cout<<"ans1:"<<ans<<endl;
}else if(a[i].x1 >= a[j].x1 && a[i].y1 >= a[j].y1 && a[j].x2 >= a[i].x2 && a[j].y2 >= a[i].y2){
area = (a[i].y2-a[i].y1) * (a[i].x2 - a[i].x1);
ans -= area;
// cout<<"ans2:"<<ans<<endl;
}
else if(a[j].x1 >= a[i].x1 && a[j].y1 >= a[i].y1 && a[j].x2 >= a[i].x2 && a[j].y2 >= a[i].y2){
area = (a[i].y2-a[j].y1) * (a[i].x2 - a[j].x1);
ans -= area;
}
else{
area = (a[j].y2-a[j].y1) * (a[j].x2 - a[j].x1);
ans -= area;
}
}
else
{
continue;
}
}
}
cout<<ans<<endl;
}
return 0;
}
/*
2
4
0 0 2 2
1 1 4 3
2 4 4 7
2 5 3 6
3
0 0 1 1
1 1 2 2
1 0 2 1
输出:
15
0
*/