Shanshan Pythoner Love CPP

hihoCoder 1040 矩形判断

2016-10-08

描述#1040 : 矩形判断

Description

给出平面上4条线段,判断这4条线段是否恰好围成一个面积大于0的矩形。

Input and Output

输入

输入第一行是一个整数T(1<=T<=100),代表测试数据的数量。

每组数据包含4行,每行包含4个整数x1, y1, x2, y2 (0 <= x1, y1, x2, y2 <= 100000);其中(x1, y1), (x2,y2)代表一条线段的两个端点。

输出

每组数据输出一行YES或者NO,表示输入的4条线段是否恰好围成矩形。

样例输入
	3
	0 0 0 1
	1 0 1 1
	0 1 1 1
	1 0 0 0
	0 1 2 3
	1 0 3 2
	3 2 2 3
	1 0 0 1
	0 1 1 0
	1 0 2 0
	2 0 1 1
	1 1 0 1

样例输出
	YES
	YES
	NO

Codes

#include <iostream>
#include <set>

using namespace std;
struct point {
    int x, y;
    bool operator<(const point& p2)const
    {
        //优先判断横坐标
        if(x<p2.x||(x==p2.x&&y<p2.y))
            return true;
        return false;
    }
    bool operator==(const point& p2) const
    {
        return (x==p2.x&&y==p2.y);
    }
};
struct line {
    point p1;
    point p2;
    
};

bool fourPoints(line lines[4]) {
    set<point> s;
    for (int i=0; i<4; i++) {
        s.insert(lines[i].p1);
        s.insert(lines[i].p2);
    }
    return s.size()==4;
}

bool isValid(line lines[4]) {
    for (int i=1; i<4; i++) {
        if ((lines[i].p1.x-lines[i].p2.x)*(lines[0].p1.x-lines[0].p2.x) ==
            (lines[i].p1.y-lines[i].p2.y)*(lines[0].p1.y-lines[0].p2.y))
            continue;
        if ((lines[i].p1.x-lines[i].p2.x)*(lines[0].p2.y-lines[0].p1.y) ==
            (lines[0].p1.x-lines[0].p2.x)*(lines[i].p1.y-lines[i].p2.y))
            continue;
        return false;
    }
    return true;
}

int main() {
    int n;
    cin >> n;
    line lines[4];
    while (n--) {
        for (int i=0; i<4; i++) {
            cin >> lines[i].p1.x >> lines[i].p1.y >> lines[i].p2.x >> lines[i].p2.y;
        }
        if (!fourPoints(lines))
            cout << "NO" << endl;
        else {
            if (!isValid(lines))
                cout << "NO" << endl;
            else
                cout << "YES" << endl;
        }
        
    }
    
    return 0;
}

Comments

Content