2015年12月15日 星期二

[UVA] 378 - Intersecting Lines

題目連結

題意:

由兩點組成一個線段,
現在給你兩條線段,要你求出這兩條線段是
平行(NONE)
重疊(LINE)
還是交於一點(POINT)
若是焦於一點則輸出該點並輸出到小數第二位。

--------------------------------------------------

我的作法:


有兩點就可以求出向量(i,j),
有向量帶入一點就可以求出方程式(jx - iy = c),
有方程式就可以求出delta, deltax, deltay;
if(delta == 0)
{
     if(deltax == 0 and deltay == 0) then 重疊
     else then 無解
}
else
{
     x = deltax / delta;
     y = deltay / delta;
}
--------------------------------------------------

程式碼:

/* 題目: UVa 378 - Intersecting Lines
 * Language: C++
 * Created on: 20151216
 *   Author: hanting
 */
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
struct Point
{
    int x, y;
};
struct Line
{
    Point s, e;
};
struct equation // ax + by = c
{
    int a, b, c;
    equation(int i, int j, int k)
    {
        a = i;
        b = j;
        c = k;
    }
};
istream& operator>>(istream& in, Point &a)
{
    in >> a.x >> a.y;
    return in;
}
istream& operator>>(istream& in, Line &a)
{
    in >> a.s >> a.e;
    return in;
}
int Determinant(int i, int j, int k, int l)
{
    return i*l - j*k;
}
Point operator - (Point &a, Point &b)
{
    Point result;
    result.x = a.x - b.x;
    result.y = a.y - b.y;
    return result;
}
int main()
{
    int testCase;
    cin >> testCase;
    cout << "INTERSECTING LINES OUTPUT" << endl;
    while(testCase--)
    {
        Line a, b;
        cin >> a >> b;
        Point v1, v2;
        v1 = a.e - a.s;
        v2 = b.e - b.s;
        equation e1(v1.y, -v1.x, v1.y*a.s.x-v1.x*a.s.y), e2(v2.y, -v2.x, v2.y*b.s.x-v2.x*b.s.y);

        double delta, deltax, deltay;
        delta = Determinant(e1.a, e1.b, e2.a, e2.b);
        deltax = Determinant(e1.c, e1.b, e2.c, e2.b);
        deltay = Determinant(e1.a, e1.c, e2.a, e2.c);
        if(delta == 0)
        {
            if(deltax == 0 and deltay == 0)
            {
                cout << "LINE" << endl;
            }
            else
            {
                cout << "NONE" << endl;
            }
        }
        else
        {
            cout << "POINT ";
            double x, y;
            x = deltax / delta;
            y = deltay / delta;
            if(fabs(x) < 1e-6) x = 0;
            if(fabs(y) < 1e-6) y = 0;
            cout << fixed << setprecision(2) << x << " " << y << endl;
        }
    }
    cout << "END OF OUTPUT" << endl;
    return 0;
}


沒有留言:

張貼留言