11664번: 선분과 점 / C++

2023. 6. 18. 19:15개인공부/코딩테스트

11664번: 선분과 점 (acmicpc.net)

 

11664번: 선분과 점

첫째 줄에 선분과 점의 좌표 Ax, Ay, Az, Bx, By, Bz, Cx, Cy, Cz가 주어진다. 좌표는 0보다 크거나 같고, 10,000보다 작거나 같은 정수이다.

www.acmicpc.net

물리엔진을 구현하기 전에 필요한 알고리즘들을 학습하자!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
 
struct Vector3
{
    double x;
    double y;
    double z;
};
 
Vector3 GetNomalize(Vector3 v)
{
    double dist = sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
 
    return Vector3{ v.x / dist, v.y / dist,v.z / dist };
}
 
double Dot(Vector3 v1, Vector3 v2)
{
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
 
double Distance(Vector3 v1, Vector3 v2)
{
    double x = v1.x - v2.x;
    double y = v1.y - v2.y;
    double z = v1.z - v2.z;
    return sqrt(x * x + y * y + z * z);
}
 
int main()
{
    ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    std::cout << std::fixed << std::setprecision(10);
 
    Vector3 P[3];
    for (int i = 0; i < 3++i)
    {
        cin >> P[i].x >> P[i].y >> P[i].z;
    }
 
    Vector3 L1 = { P[1].x - P[0].x, P[1].y - P[0].y , P[1].z - P[0].z };
    Vector3 L2 = { P[2].x - P[0].x, P[2].y - P[0].y , P[2].z - P[0].z };
 
    Vector3 nomalL1 = GetNomalize(L1);
 
    double f = Dot(nomalL1, L2);
    double P0P1 = Distance(P[0], P[1]);
 
    if (f < 0)
    {
        cout << Distance(P[0], P[2]);
    }
    else if (f < P0P1)
    {
        double dist = sqrt(Distance(P[0], P[2]) * Distance(P[0], P[2]) - f * f);
        cout << dist;
    }
    else
    {
        cout << Distance(P[1], P[2]);
    }
 
 
 
    return 0;
}
 
cs