지구정복

[DP] 백준 - 설탕배달 본문

데이터 엔지니어링 정복/Algorithm

[DP] 백준 - 설탕배달

nooh._.jl 2021. 7. 15. 21:14
728x90
반응형

-자바

package dp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;

public class Sugar1 {
	private static BufferedWriter bw = 
			new BufferedWriter( new OutputStreamWriter(System.out));
	private static int n;
	private static int[] d;

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		n = Integer.parseInt( br.readLine() );
		d = new int[5001];
		Arrays.fill( d, 5000 );
		if( n<5 ) {
			if( n == 3) {
				bw.write( 1 + "\n" );
				bw.flush();
			} else {
				bw.write( -1 + "\n" );
				bw.flush();
			}
			return;
		}
		
		d[3] = d[5] = 1;
		
		for( int i=6; i<=n; i++ ) d[i] = Math.min( d[i-3]+1, d[i-5]+1 );
		
		if( d[n] > 5000) {
			bw.write( -1 + "\n" );
			bw.flush();
		} else {
			bw.write( d[n] + "\n" );
			bw.flush();
		}
		
		bw.close();
		br.close();
	}
}

 

-파이썬

n = int(input())
d = [5000] * (n+1)
if n <= 5:
    if n == 3 or n == 5: 
        print( 1 )
    else:
        print( -1 )
else: 
    d[3] = 1
    d[5] = 1
    for i in range( 6, n+1 ):
        d[i] = min( d[i-3]+1, d[i-5]+1 )

    if d[i] > 5000:
        print( -1 )
    else:
        print( d[n] )
728x90
반응형

'데이터 엔지니어링 정복 > Algorithm' 카테고리의 다른 글

[DP] 백준 - BABBA  (0) 2021.07.16
[DP] 백준 - 퇴사2  (0) 2021.07.16
[문자열] 백준 - Pen Pineapple Apple Pen  (0) 2021.07.15
[DP] 백준 - 피보나치 수 5  (0) 2021.07.15
[DP] 백준 - 제곱수의 합  (0) 2021.07.15
Comments