-
[KOITP] 꽃 진열자료구조 및 알고리즘/문제풀이 2017. 1. 9. 19:59
시간 제한 메모리 제한 제출 횟수 정답 횟수 (비율) 정답자 수 1.0 초 512 MB 431 106 (25%) 78 < Comment >
그다지 어려운 문제는 아니었는데, 문제를 정의할 때, 꽃병의 갯수와 꽃의 갯수를 착각해서 점화식을 세우고도 조금 헷갈려서 오래 걸렸습니다. 기본적으로 발상은 A번째 꽃병까지 B개의 꽃을 때의 최대 아름다움을 기준으로 DP 함수를 정의하고, 시작하였습니다. 기저 케이스는 꽃병의 수와 꽃의 수가 같을 경우 차례대로 넣는 경우입니다.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class Flower { public static int F = 0; public static int V = 0; public static int matrix[][] = null; public static int dp[][] = null; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); F = Integer.parseInt(st.nextToken()); V = Integer.parseInt(st.nextToken()); matrix = new int[F+1][V+1]; dp = new int[F+1][V+1]; for (int i = 1 ; i <= F ; i++) { st = new StringTokenizer(br.readLine()); for (int j = 1 ; j <= V ; j++) { matrix[i][j] = Integer.parseInt(st.nextToken()); } } for (int i = 1 ; i <= F ; i++) { for (int j = i ; j <= V ; j++) { if (i == j) { int temp = 0; for (int k = 1 ; k <= i ; k++) { temp += matrix[k][k]; } dp[i][j] = temp; } else { dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j-1] + matrix[i][j]); } } } bw.write("" + dp[F][V]); bw.flush(); bw.close(); } }