【数学】IoU

IoU

 FZU - 2300 

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

题目大意:

先输入一个整数t,代表有t组测试,对于每组测试,输入两行,每行四个整数x,y,dx,dy,代表矩形的左下角的坐标以及它的长和宽,问这两个矩形的重合面积/这两个矩形组成的区域的面积是多少。

解题思路:

直接求解即可,需要判断一下不重合的情况。

代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define inf 0x3f3f3f3f
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define lep(i,l,r) for(int i=l;i>=r;i--)
#define ms(arr) memset(arr,0,sizeof(arr))
//priority_queue ,greater >q;
const int maxn = (int)1e5 + 5;
const ll mod = 1e9+7;
int main() 
{
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    //freopen("out.txt", "w", stdout);
    ios::sync_with_stdio(0),cin.tie(0);
    int t;
    scanf("%d",&t);
    while(t--) {
    	int x1,x2,x3,x4,y1,y2,y3,y4;
    	int x,y,dx,dy;
    	scanf("%d %d %d %d",&x,&y,&dx,&dy);
    	x1=x;y1=y;x2=x+dx;y2=y+dy;
    	double t=dx*dy;
    	scanf("%d %d %d %d",&x,&y,&dx,&dy);
    	x3=x;y3=y;x4=x+dx;y4=y+dy;
    	t=t+dx*dy;
    	double t1=min(x2,x4)-max(x1,x3);
    	double t2=min(y2,y4)-max(y1,y3);
    	if(t1<0||t2<0) printf("0.00\n");
    	else printf("%.2f\n",(t1*t2)/(t-t1*t2));
    }

    return 0;
}

 

你可能感兴趣的:(数学)