문제 : https://www.acmicpc.net/problem/1149


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[][] street = new int[n][3];
        int d[][] = new int[n][3];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                street[i][j] = scan.nextInt();
            }
        }
        // 입력부
        for (int j = 0; j < n; j++) {
            for (int i = 0; i < 3; i++) {
                if (j == 0) {
                    d[j][i] = street[j][i];
//                    System.out.print(d[j][i] + " ");
                } else {

                    d[j][i] = Math.min(d[j - 1][(i + 1) % 3], d[j - 1][(i + 2) % 3]) + street[j][i];
//                    System.out.print(d[j][i] + " ");
                }
            }
//            System.out.println();
        }

//        for (int a : d[n - 1]) {
//            System.out.println(a);
//        }
        System.out.println(Math.min(d[n-1][0],Math.min(d[n-1][1], d[n-1][2])));

        scan.close();
    }

}

문제 : https://www.acmicpc.net/problem/2748


간단하게 구현할 수 있는 피보나치 수열에 동적계획법을 적용해봤다.

배열을 만들어서 피보나치 메소드에 배열의 위치를 알려주어 한번 계산한 피보나치수는 다시 계산하지 않도록 만들었다.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		//피보나치
		
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		long [] arr = new long [n+1];
		for( int i = 0 ; i < arr.length; i ++) {
			arr[i] = -1;
		}
		System.out.println(fi(n, arr));
//		for(int a : arr) {
//			System.out.print(a+" ");
//		}
		scan.close();
	}
	static long fi(int num,long [] arr) {
		if(arr[num] != -1) {
			return arr[num];
		}
		if (num == 0 || num == 1) {
			arr[num] = num;
			return num;
		} else {
			long result = fi(num-1,arr) + fi(num-2,arr);
			arr[num] = result;
			return result;
		}
	}

}

+ Recent posts

"여기"를 클릭하면 광고 제거.