[BaekJoon] #14910 - 오르막 [Java][C++][Python]
[BaekJoon] #14910 - 오르막 [Java][C++][Python]
1. 아이디어
주어진 정수들이 비내림차순인지 판정하는 문제로, 이웃한 쌍마다 앞의 수가 뒤의 수 이하이면 부등호가 이어져 수열 전체가 비내림차순이므로 이웃끼리만 비교하면 된다. 개수 $N$은 입력에 따로 없고 한 줄에 수만 주어지므로 줄의 끝까지 읽는다.
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
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));
StringTokenizer st = new StringTokenizer(br.readLine());
int prv = -1_000_000;
while (st.hasMoreTokens()) {
int x = Integer.parseInt(st.nextToken());
if (x >= prv) {
prv = x;
} else {
System.out.println("Bad");
return;
}
}
System.out.println("Good");
}
}
원소의 최솟값인 -1,000,000을 직전 값의 초기값으로 두어 첫 수가 항상 통과하게 했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int prv = -1'000'000;
int x;
while (cin >> x) {
if (x >= prv) {
prv = x;
} else {
cout << "Bad";
return 0;
}
}
cout << "Good";
}
while (cin >> x)는 더 읽을 수 없으면 끝나므로 개수를 몰라도 입력 끝까지 받았다. 직전 값의 초기값은 원소의 최솟값인 -1,000,000으로 두었다.
1
2
3
4
5
6
import sys
input = sys.stdin.readline
arr = list(map(int, input().split()))
print("Good" if arr == sorted(arr) else "Bad")
정렬한 결과가 원래 리스트와 같으면 이미 비내림차순이므로 sorted(arr)와 비교했다.
This post is licensed under CC BY 4.0 by the author.