[BaekJoon] #9366 - 삼각형 분류 [Java][C++][Python]
[BaekJoon] #9366 - 삼각형 분류 [Java][C++][Python]
1. 아이디어
세 변의 길이로 삼각형이 만들어지는지 확인하고, 만들어지면 종류를 분류하는 문제다. 어느 한 변이라도 나머지 두 변의 합 이상이면 삼각형이 만들어지지 않으며, 세 변을 각각 확인하면 가장 긴 변을 따로 찾지 않아도 된다.
이 확인은 분류보다 먼저 해야 하는데, 2, 2, 4처럼 두 변이 같아도 삼각형이 되지 않는 입력이 있기 때문이다. 또 정삼각형도 두 변이 같다는 조건을 만족하므로 두 변이 같은지보다 세 변이 모두 같은지를 먼저 본다.
2. 코드
풀이 [Java][C++][Python]
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
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int t = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= t; tc++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
if (a >= b + c || b >= a + c || c >= a + b) {
sb.append("Case #").append(tc).append(": invalid!\n");
} else if (a == b && b == c) {
sb.append("Case #").append(tc).append(": equilateral\n");
} else if (a == b || b == c || c == a) {
sb.append("Case #").append(tc).append(": isosceles\n");
} else {
sb.append("Case #").append(tc).append(": scalene\n");
}
}
System.out.println(sb);
}
}
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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
int a, b, c;
cin >> a >> b >> c;
if (a >= b + c || b >= a + c || c >= a + b) {
cout << "Case #" << tc << ": invalid!\n";
} else if (a == b && b == c) {
cout << "Case #" << tc << ": equilateral\n";
} else if (a == b || b == c || c == a) {
cout << "Case #" << tc << ": isosceles\n";
} else {
cout << "Case #" << tc << ": scalene\n";
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys
input = sys.stdin.readline
t = int(input())
for tc in range(1, t + 1):
a, b, c = map(int, input().split())
if a >= b + c or b >= a + c or c >= a + b:
res = "invalid!"
elif a == b == c:
res = "equilateral"
elif a == b or b == c or c == a:
res = "isosceles"
else:
res = "scalene"
print(f"Case #{tc}: {res}")
a == b == c처럼 비교를 이어 써서 세 변이 모두 같은지 확인했다.
This post is licensed under CC BY 4.0 by the author.