fbpx

Problema #930 – IntersectieSegmente – Rezolvari PBInfo

de Mihai-Alexandru

Cerința

Se dau două segmente în plan, specificate prin coordonatele capetelor. Să se verifice dacă au cel puțin un punct comun.

Date de intrare

Fișierul de intrare intersectiesegmente.in conține pe prima linie 8 numere naturale separate prin spații, respectiv: X1, Y1, X2, Y2, X3, Y3, X4, Y4. Primul segment are capetele (X1, Y1) și (X2, Y2).

Date de ieșire

Fișierul de ieșire intersectiesegmente.out va conține pe prima linie DA (când segmentele se intersectează) sau NU (în caz contrar).

Restricții și precizări

  • Numerele din fișierul de intrare sunt întregi cuprinse între -1001 și 1001.
  • Ambele segmente au lungimea nenulă.

Exemplu

intersectiesegmente.in

-1 -1 1 1 -1 1 1 -1

intersectiesegmente.out

DA
#include <bits/stdc++.h>
using namespace std;

ifstream fin("intersectiesegmente.in");
ofstream fout("intersectiesegmente.out");

int X1, Y1, X2, Y2, X3, Y3, X4, Y4, d1, d2, d3, d4;
int det(int X1, int Y1, int X2, int Y2, int X3, int Y3)
{
    return (X2-X1)*(Y3-Y1) - (X3-X1)*(Y2-Y1);
}

int pctsegm(int x1, int y1, int x2, int y2, int x3, int y3)
{
    int d = det(x1, y1, x2, y2, x3, y3);
    if (d!=0)
        return 0;
    if (x1 == x3 && y1 == y3)
        return 1;
    if (x2 == x3 && y2 == y3)
        return 1;
    if ((x3-x1) * (x3-x2) < 0 || (y3-y1) * (y3-y2) < 0)
        return 1;
    else
        return 0;
}

int main()
{
    fin >> X1 >> Y1 >> X2 >> Y2 >> X3 >> Y3 >> X4 >> Y4;
    if (pctsegm(X1, Y1, X2, Y2, X3, Y3))
        fout << "DA";
    else
    if (pctsegm(X1, Y1, X2, Y2, X4, Y4))
        fout << "DA";
    else
    if (pctsegm(X3, Y3, X4, Y4, X1, Y1))
        fout << "DA";
    else
    if (pctsegm(X3, Y3, X4, Y4, X2, Y2))
        fout << "DA";
    else
    {
        d1 = det(X3, Y3, X4, Y4, X1, Y1);
        d2 = det(X3, Y3, X4, Y4, X2, Y2);
        d3 = det(X1, Y1, X2, Y2, X3, Y3);
        d4 = det(X1, Y1, X2, Y2, X4, Y4);

        if (d1 * d2 < 0 && d3 * d4 < 0)
            fout << "DA";
        else
            fout << "NU";
    }
}
Comentarii

S-ar putea sa iti placa