[백준 22421] Koto Municipal Subway (C#, C++) - soo:bak
작성일 :
문제 링크
22421번 - Koto Municipal Subway
설명
x + y = D를 만족하는 격자점 중 원점까지의 거리가 예산 E와 가장 가까운 점을 찾아, 그 차이의 최솟값을 구하는 문제입니다.
접근법
x를 0부터 D까지 순회하면서 y = D - x로 정합니다. 각 점에서 원점까지의 거리를 계산하고, E와의 차이의 절댓값 중 최솟값을 구합니다. D가 100 이하이므로 모든 경우를 확인해도 충분합니다.
Code
C#
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
using System;
class Program {
static void Main() {
while (true) {
var line = Console.ReadLine();
if (line == null) break;
var parts = line.Split();
var d = int.Parse(parts[0]);
var e = int.Parse(parts[1]);
if (d == 0 && e == 0) break;
var best = double.MaxValue;
for (var x = 0; x <= d; x++) {
var y = d - x;
var dist = Math.Sqrt(x * x + y * y);
var diff = Math.Abs(dist - e);
if (diff < best) best = diff;
}
Console.WriteLine(best.ToString("F10"));
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int d, e;
while (cin >> d >> e) {
if (d == 0 && e == 0) break;
double best = 1e18;
for (int x = 0; x <= d; x++) {
int y = d - x;
double dist = hypot((double)x, (double)y);
double diff = fabs(dist - e);
if (diff < best) best = diff;
}
cout << fixed << setprecision(10) << best << "\n";
}
return 0;
}