CC36:平分的直线

题目

在二维平面上,有两个正方形,请找出一条直线,能够将这两个正方形对半分。假定正方形的上下两条边与x轴平行。
给定两个vecotrA和B,分别为两个正方形的四个顶点。请返回一个vector,代表所求的平分直线的斜率和截距,保证斜率存在。
测试样例:

[(0,0),(0,1),(1,1),(1,0)],[(1,0),(1,1),(2,0),(2,1)]`
返回:[0.0,0.5]

解法

简单的求斜率、截距问题,既然要平分2个正方形就可以让这条直线经过两个正方形的中心。不过在这里要注意题目的测试数据可能是乱序给出的,即四个顶点但并不是按一定顺序排列的,我们在进行处理时需要先简单排序一下,代码如下:

/*
struct Point {
    int x;
    int y;
    Point() :
            x(0), y(0) {
    }
    Point(int xx, int yy) {
        x = xx;
        y = yy;
    }
};*/
class Bipartition {
public:
    static bool cmp(const Point &A,const Point &B)
    {
        if(A.x!=B.x)
            return A.x<B.x;
        return A.y<B.y;
    }
    
    vector<double> getBipartition(vector<Point> A, vector<Point> B) {
        // write code here
        sort(A.begin(),A.end(),cmp);
        sort(B.begin(),B.end(),cmp);
        double x1=(A[0].x+A[3].x)/2;
        double x2=(B[0].x+B[3].x)/2;
        double y1=(A[0].y+A[3].y)/2;
        double y2=(B[0].y+B[3].y)/2;
        double k=(y1-y2)/(x1-x2);
        double b=y1-k*x1;
        res.push_back(k);
        res.push_back(b);
        return res;
    }
private:
    vector<double> res;
};
posted @ 2018-08-01 10:48  MrYun  阅读(367)  评论(0编辑  收藏  举报