poj 1269 Intersecting Lines

来源:互联网 发布:下载淘宝网软件 编辑:程序博客网 时间:2024/06/04 18:54

最近跟么长大脑一样,人家明明让求直线,,,我还大半夜求了两个点的线段。。。无数次WA, 今天早上才反应过来



我们先来熟悉几个概念

 已知向量a (p1,p2),b(p3,p4) ( p1(x1, y1) , p2(x2,y2) ,p3(x2,y3), p4(x4,y4))

      如果两向量平行那么 就有 a.x*b.y - b.x*a.y == 0(也就是本题NONE的情况

      如果两向量共线那么  我们就可以利用差积来求解 设 起点 s, 终点e  Across(p1, p2, p3) == 0&&Across(p1,p2,p4) == 0 因为是直线所以只满足两个就一定共线 (LINE)

   如果两个向量相交, 且交点为P(x0,y0)

   那么 (p1,p2, P,  ) (p3, p4, P) 一定共线, 即差积为0

  那么就有   (y1-y2)x1 + (x2-x1)y1  +  x1y2 -x1y2 = 0;

                     (y3-y4)x3 + (x4-x3)y3  + x3y4 -x4y3 = 0;

   接下来就是二元一次方程组求解

    a1x + b1y + c2 = 0,  a2x +b2y + c2 =0

    x = (b1*c2 - b2*c1)/(a1*b2 - a2*b1);
    y = (a2*c1 - a1*c2)/(a1*b2 - a2*b1);

由于我们已经先求出了平行的情况所以(a1*b2 - a2*b1)  != 0 

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>


using namespace std;
#define eps 1e-8
int sid(double a)
{
    if(a > eps)
        return 1;
    if(a < -eps)
        return -1;
    return 0;
}
struct Point
{
    double x, y;
    Point() {};
    Point(double a, double b)
    {
        x = a;
        y = b;
    }
} sta[4];


double Across(Point a, Point b, Point c)
{
    return (b.x - a.x) * (c.y - a.y) - (c.x - a.x)*(b.y - a.y);
}


void solve()
{
    double s1,s2,s3,s4;
    int d1, d2,d3,d4;
    d1 = sid(s1 = Across(sta[0], sta[1], sta[2]));
    d2 = sid(s2 = Across(sta[0], sta[1], sta[3]));
//    d3 = sid(s3 = Across(sta[2], sta[3], sta[0]));
//    d4 = sid(s4 = Across(sta[2], sta[3], sta[1]));
    if(d1 == 0 && d2 == 0)
    {
        printf("LINE\n");
        return ;
    }
    if(sid((sta[0].x - sta[1].x)*(sta[2].y - sta[3].y) - (sta[0].y - sta[1].y)*(sta[2].x - sta[3].x)) == 0)
    {
        printf("NONE\n");
        return ;
    }
    double a1 = sta[0].y - sta[1].y;
    double b1 = sta[1].x - sta[0].x;
    double c1 = sta[0].x*sta[1].y - sta[1].x*sta[0].y;
    double a2 = sta[2].y - sta[3].y;
    double b2 = sta[3].x - sta[2].x;
    double c2 = sta[2].x*sta[3].y - sta[3].x*sta[2].y;
    //cout<<a1<<b1<<c1<<a2<<b2<<c2<<endl;
    double x = (b1*c2 - b2*c1)/(a1*b2 - a2*b1);
    double y = (a2*c1 - a1*c2)/(a1*b2 - a2*b1);
    printf("POINT %.2lf %.2lf\n", x, y);
}
int main()
{
    int n;
    scanf("%d",&n);
    printf("INTERSECTING LINES OUTPUT\n");
    while(n--)
    {
        double x, y;
        for( int i = 0; i < 4; i++)
        {
            scanf("%lf %lf",&x, &y);
            sta[i] = Point(x, y);
        }
        solve();
    }
    printf("END OF OUTPUT\n");
    return 0;
}

0 0
原创粉丝点击