Problem 2300 IoU
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
题目大意
给2个正方形,计算相交的区域的面积除以两个正方形总面积。
解题思路
主要难点在于判断相交区域。只要两个正方形左下角的点最大的x小于右上角的点最小的x,并且左下角的的点最大的y小于右上角的最小的y则两个正方形相交。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int x1, y1, w1, h1, x2, y2, w2, h2;
int main()
{
int t;
cin >> t;
while (t--)
{
cin >> x1 >> y1 >> w1 >> h1;
cin >> x2 >> y2 >> w2 >> h2;
int o; //相交面积
if(min(x1+w1, x2+w2) - max(x1, x2) > 0 && min(y1+h1, y2+h2) - max(y1, y2) > 0)
o = (min(x1 + w1, x2 + w2) - max(x1, x2))
* (min(y1 + h1, y2 + h2) - max(y1, y2));
else
o = 0;
double ans;
if(w1 * h1 + w2 * h2 - o > 0)
ans = (double)o / (w1 * h1 + w2 * h2 - o);
else
ans = 0;
printf("%.2f\n", ans);
}
return 0;
}
总结
难点在于判断相交区域。

浙公网安备 33010602011771号