알고리즘 문제
백준 (BOJ) 23351 물주기 java 그리디
veryhi
2022. 6. 10. 16:22
https://www.acmicpc.net/problem/23351
23351번: 물 주기
첫째 줄에 자연수 $N$, $K$, $A$, $B$가 공백을 사이에 두고 주어진다. ($2 \le N \le 100$, $1 \le K \le 100$, $1 \le A \times B < N$, $A$는 $N$의 약수)
www.acmicpc.net
첫 번째 풀이는 끝 화분에 물을 줘야하는 순간에 끝에서 시작하여 앞쪽으로 주는 방식이다. 이후 상태 초기화.
두 번째 풀이는 끝 화분에 물을 줘야하는 순간에 끝에서 벗어난 만큼을 앞 화분들에 연속적으로 주는 방식이다.
조건이 더 붙는다면 둘 중 하나로만 풀어야 할지도?
배열을 아래처럼 어렵게 돌리는 방법 말고 % 연산자를 활용하는 방법도 있다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
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()),k = Integer.parseInt(st.nextToken()),
a = Integer.parseInt(st.nextToken()),b = Integer.parseInt(st.nextToken());
int[] pots = new int[n];
Arrays.fill(pots, k);
int nMinus1 = n-1; // 항상 끝에 거만 체크하면 되지 않을까?
int count = 0;
int startPointCheck=0, lastPointCheck=0;
boolean flag = true;
while (pots[nMinus1]!=0){
++count;
lastPointCheck = startPointCheck + a;
if(n <= lastPointCheck){
flag = false;
}
// watering
if(flag){ // 정상 범위 동작
for(int i=startPointCheck; i<lastPointCheck; ++i){
pots[i] += b;
}
startPointCheck = lastPointCheck;
}
else{ // 범위를 넘어섰다면 한번만 뒤에서
for(int i=nMinus1; nMinus1-a<i; --i){
pots[i] += b;
}
flag = true;
startPointCheck = 0;
}
for(int i=0; i<n; ++i){
--pots[i];
}
}
System.out.print(count);
}
}
% 활용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
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()),k = Integer.parseInt(st.nextToken()),
a = Integer.parseInt(st.nextToken()),b = Integer.parseInt(st.nextToken());
int[] pots = new int[n];
Arrays.fill(pots, k);
int count = 0, startPoint=0, endPoint;
while (true){
count += 1;
endPoint = startPoint+a;
for(int i=startPoint; i<endPoint; ++i){
pots[i%n] += b;
}
for(int i=0; i<n; ++i){
if(--pots[i] == 0){
System.out.print(count);
return;
}
startPoint = endPoint % n;
}
}
}
}