https://www.acmicpc.net/problem/24337
24337번: 가희와 탑
일직선으로 다양한 높이의 건물들이 N개 존재합니다. 가희는 건물들의 왼쪽에, 단비는 건물들의 오른쪽에 있습니다. 일직선 상에 가희와 단비, 건물들은 아래와 같은 순서로 배치되어 있습니다.
www.acmicpc.net
풀이방법
예시(N : 9, A : 4, B : 3)
1. A의 값을 먼저 채워준다. (N-B 부터 차례로)
2. B의 값을 채워준다.(A값이 차있을 시, 비교 해서 더 큰 값으로 둔다)
3. A,B 가 1인 경우 예외가 있기 때문에 처리 해 줘야한다.
A가 1인 경우 -> N-B 칸(제일 큰 값이 들어있는 칸)을 제거 한 후, 제일 앞 (building[0]) 에 MAX값을 넣는다.
ex) N : 9 , A : 1, B : 4
B가 1인 경우 -> 마지막 칸에 MAX 값을 넣어주기만 하면 된다.
4. 출력 시, 빈칸을 1 로 채워 출력한다.
소스코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N,A,B;
static int building[];
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
StringBuilder sb = new StringBuilder();
N = Integer.parseInt(st.nextToken());
A = Integer.parseInt(st.nextToken());
B = Integer.parseInt(st.nextToken());
building = new int[N];
//볼 수 없는 경우
if(A+B >= N+2) {
System.out.println(-1);
return;
}
int tempA = A;
//최대한 뒤부터 먼저 채워줌
if(A != 1) {
for (int i = N-B; i > N-B-A; i--) {
building[i] = tempA;
tempA--;
}
}
int tempB = B;
if(B == 1) {
building[N-1] = Math.max(A, B);
}else {
for (int i = N-B; i < N; i++) {
if(building[i] > tempB) {
tempB--;
continue;
}
building[i] = tempB;
tempB--;
}
}
//B 다채우고 A가 1일 때 마지막 숫자 제거 & 첫번째에 최댓값 넣기
if(A == 1) {
building[N-B] = 0;
building[0] = B;
}
//빈칸일 때, 1로 출력
for (int i = 0; i < N; i++) {
if(building[i] == 0) {
sb.append(1).append(" ");
}else {
sb.append(building[i]).append(" ");
}
}
System.out.println(sb.toString());
}
}
결과
'Algorithm > java' 카테고리의 다른 글
백준 1949 JAVA : 우수 마을 (0) | 2023.04.25 |
---|---|
백준 16724 JAVA : 피리 부는 사나이 (0) | 2023.04.25 |
백준 9328 JAVA : 열쇠 (2) | 2023.04.25 |
순열(permutation) 구현 (1) | 2023.04.12 |
백준 11053 JAVA : 가장 긴 증가하는 부분 수열(LIS) (0) | 2023.03.31 |