![[백준 / BOJ] 1004번 어린 왕자 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FUhHCL%2FbtrJp0W5dKd%2FJFAcKz8uIoPXrEH49Plr1K%2Fimg.png)
[백준 / BOJ] 1004번 어린 왕자 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 6. 5. 01:45
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/1004
1004번: 어린 왕자
입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 그 다음 줄부터 각각의 테스트케이스에 대해 첫째 줄에 출발점 (x1, y1)과 도착점 (x2, y2)이 주어진다. 두 번째 줄에는 행성계의 개수 n이 주
www.acmicpc.net
문제

문제 풀이
터렛 문제와 유사한 아이디어를 가진다. 사진과 코드의 주석을 참고하면 된다.
1번의 경우에는 dist1 < radius, dist2 > radius 이므로 경유해야 한다. 이는 dist1과 dist2가 바뀌어도 성립한다.
2번의 경우에는 dist1 < radius, dist2 < radius 이므로 경유 자체를 하지 않아도 된다.

C++ 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int T; | |
std::cin >> T; | |
for (int t = 0; t < T; ++t) { | |
int cnt = 0, n, x1, y1, x2, y2; // 출발점, 도착점 | |
std::cin >> x1 >> y1 >> x2 >> y2; | |
std::cin >> n; | |
for (int k = 0; k < n; ++k) { | |
int x, y, r; | |
std::cin >> x >> y >> r; | |
// 출발점과 행성계 거리, 도착점과 행성계 거리 | |
int dist1 = (x1 - x) * (x1 - x) + (y1 - y) * (y1 - y); | |
int dist2 = (x2 - x) * (x2 - x) + (y2 - y) * (y2 - y); | |
int radius = r * r; | |
// 출발점 - 행성계 거리가 radius보다 크고, 도착점 - 행성계 거리가 radius보다 크면 경유할 의미가 없음. 둘 중 하나만 크면 경유함 | |
if (dist1 < radius && dist2 < radius) | |
continue; | |
else if (dist1 < radius || dist2 < radius) | |
cnt++; | |
} | |
std::cout << cnt << "\n"; | |
} | |
return 0; | |
} |
Python 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
input = sys.stdin.readline | |
T = int(input()) | |
for i in range(T): | |
cnt = 0 | |
x1, y1, x2, y2 = map(int, input().split()) | |
n = int(input()) | |
for i in range(n): | |
x, y, r = map(int, input().split()) | |
dist1 = (((x1 - x) ** 2) + ((y1 - y) ** 2)) | |
dist2 = (((x2 - x) ** 2) + ((y2 - y) ** 2)) | |
radius = r * r | |
if dist1 < radius and dist2 < radius: | |
continue | |
elif dist1 < radius or dist2 < radius: | |
cnt += 1 | |
print(cnt) |
소감
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 5086번 배수와 약수 (C++, Python) (0) | 2022.06.06 |
---|---|
[백준 / BOJ] 1358번 하키 (C++, Python) (0) | 2022.06.05 |
[백준 / BOJ] 1002번 터렛 (C++, Python) (0) | 2022.06.04 |
[백준 / BOJ] 2477번 참외밭 (C++, Python) (0) | 2022.06.03 |
[백준 / BOJ] 3009번 네 번째 점 (C++, Python) (0) | 2022.06.02 |
@Reo :: 코드 아카이브
자기계발 블로그