題目:
Xzz need to calculate Intersection over Union(IoU) of two rectangles, can you help him?
rectangle (x, y, w, h) means a rectangle MNPQ, M(x,y), N(x, y+h), P(x+w, y+h), Q(x+w, y).
IoU = Area of overlap / Area of union.
Input
First line of the input file contains an integer T(0 < T <= 100) that indicates how many cases of inputs are there.
The description of each case is given below:
The first line of each input set contains integer x1, y1, w1, h1.
The second line of each input set contains integer x2, y2, w2, h2.
0 ≤ x, y, w, h ≤ 100000
Output
The description of output for each test case is given below:
The first line of the output for each test case contains number k- the IoU of two rectangles.
Output should be rounded to 2 digits after decimal point.
Sample Input
2
1 1 1 1
1 1 2 2
1 1 2 1
1 1 1 2
Sample Output
0.25
0.33
題意:
輸入兩組各四個(gè)數(shù)據(jù)按照一定的方式計(jì)算為兩個(gè)矩形的四點(diǎn)坐標(biāo),計(jì)算兩矩形重合面積和合并面積的比值
解題思路:
要算兩個(gè)面積就分開(kāi)討論:
重合面積:
由于是矩形,所以知道兩個(gè)對(duì)角點(diǎn)的坐標(biāo)就可以計(jì)算重合面積的大小了耙旦。
首先在橫縱坐標(biāo)中找到兩個(gè)中間值也就是一共四個(gè)值测垛,用它來(lái)分別表示重合面積四個(gè)邊在坐標(biāo)系中的橫縱坐標(biāo)的值,再相減得到重合矩形的長(zhǎng)寬却汉,即可得到該面積驯妄。
合并面積:直接運(yùn)算,相加后再減去重合面積即可
這道題還是有坑點(diǎn)合砂,要考慮是否相交青扔。寫(xiě)完了也沒(méi)檢查直接交了一發(fā),WA后檢查發(fā)現(xiàn)在計(jì)算合并面積之后沒(méi)有減去多加的重合面積(小坑點(diǎn),但是自己不檢查這個(gè)習(xí)慣真的很大微猖,太自信了)
AC代碼:
#include<iostream>
#include<cstdio>
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
double area_o;
using namespace std;
double area_over(int m1,int n1,int m2,int n2)
{
if(m2>m1 && n2>n1)
area_o=(m2 -m1)*(n2-n1);
else
area_o=0.00;
return 0;
}
int main(int argc, char const *argv[])
{
int n;
cin>>n;
double m1,n1,m2,n2;
double area1=0,area2=0,area_union=0;
double IoU=0;
int x1,x2,y1,y2,w1,w2,h1,h2;
for(int i=0;i<n;i++){
cin>>x1>>y1>>w1>>h1;
cin>>x2>>y2>>w2>>h2;
m1 = max(min(x1,x1+w1),min(x2,x2+w2));
n1 = max(min(y1+h1,y1),min(y2,y2+h2));
m2 = min(max(x1,x1+w1),max(x2,x2+w2));
n2 = min(max(y1+h1,y1),max(y2,y2+h2));
area_over(m1,n1,m2,n2);
area1=w1*h1;area2=w2*h2;
area_union=area1+area2;
IoU=(area_o*1.0)/((area_union-area_o)*1.0);
printf("%.2lf\n",IoU);
}
return 0;
}