728x90
완전 탐색으로 첨탑 높이 비교
시도1
import java.util.*;
import java.io.*;
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 n = Integer.parseInt(st.nextToken());
int[] data = new int[n];
st = new StringTokenizer(br.readLine());
for (int i=0; i < n; i++) {
data[i] = Integer.parseInt(st.nextToken());
}
int count = 0;
List<Integer> newData = new ArrayList<Integer>();
count = 1; //맨 처음 첨탑 밀고
for (int i=1; i < n-1; i++){
if (data[i] <= data[i+1]){ //두번째 첨탑부터 비교
count += 1;
}
if (i+1 == n-1) { //1 3 2 5 8 1 일 경우 1, 3, 5 넘어뜨리고 8도 넘어뜨려야함. 위에 조건문으로는 count가 안됨
count += 1;
}
}
System.out.print(count);
}
}
주어진 입력은 다 맞는데.. 반례가 있나보다..
다시 시도
시도 2 (성공)
import java.util.*;
import java.io.*;
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 n = Integer.parseInt(st.nextToken());
int[] data = new int[n];
st = new StringTokenizer(br.readLine());
for (int i=0; i < n; i++) {
data[i] = Integer.parseInt(st.nextToken());
}
int count = 0;
List<Integer> newData = new ArrayList<Integer>();
count = 1; //처음 첨탑은 무조건 넘어뜨림.
for (int i=0; i < n-1; i++){ //이전 첨탑data[i]보다 다음 첨탑(data[i+1]이 크면 count++, 다음 첨탑을 기준으로 count
if (data[i] <= data[i+1]){
count++;
}
}
System.out.print(count);
}
}
다른 사람 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays; public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int ans = 1;
for (int i = 1; i < array.length; i++) {
if (array[i - 1] <= array[i]) {
ans++;
}
}
System.out.println(ans);
}
}
BufferedReader로 읽은걸 mapToInt로 int로 바꾸고 .toArray()로 배열로 변환
int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[파이썬] 10870 피보나치 수 5 (0) | 2024.04.10 |
---|---|
14916 거스름돈 (0) | 2024.04.10 |
11328 Strfry (0) | 2024.03.31 |
13300 방 배정 (0) | 2024.03.31 |
3273: 두 수의 합 (2) | 2024.03.23 |