Bobjoehi

CombiningRiceballs

Dec 19th, 2020
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class CombiningRiceballs{
  5.    
  6.     static int[][] dp;
  7.     static boolean[][] comb;
  8.    
  9.     public static void main (String[] args) throws IOException{
  10.         readLine();
  11.         int n = nextInt();
  12.        
  13.         dp = new int[n][n];
  14.         comb = new boolean[n][n];
  15.        
  16.         readLine();
  17.         for(int i = 0; i < n; i ++) {
  18.             dp[i][i] = nextInt();
  19.             comb[i][i] = true;
  20.         }
  21.        
  22.         for(int d = 1; d < n; d ++) {
  23.             for(int i = 0, j = d; j < n; i ++, j ++) {
  24.                 boolean found = false;
  25.                 for(int k = i; k < j && !found; k ++) {
  26.                     if(comb[i][k] && comb[k + 1][j]) {
  27.                         if(dp[i][k] != dp[k + 1][j]) {
  28.                             dp[i][j] = Math.max(dp[i][j], Math.max(dp[i][k], dp[k + 1][j]));
  29.                             comb[i][j] = false;
  30.                         }else {
  31.                             dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][j]);
  32.                             comb[i][j] = true;
  33.                             found = true;
  34.                         }
  35.                     }else {
  36.                         dp[i][j] = Math.max(dp[i][j], Math.max(dp[i][k], dp[k + 1][j]));
  37.                     }
  38.                 }
  39.                
  40.                 for(int k = i; k < j && !found; k ++) {
  41.                     for(int l = k + 1; l < j && !found; l ++) {
  42.                         if(comb[i][k] && comb[k + 1][l] && comb[l + 1][j]) {
  43.                             if(dp[i][k] == dp[l + 1][j]) {
  44.                                 dp[i][j] = Math.max(dp[i][j], dp[i][k] + dp[k + 1][l] + dp[l + 1][j]);
  45.                                 comb[i][j] = true;
  46.                                 found = true;
  47.                             }
  48.                         }
  49.                     }
  50.                 }
  51.             }
  52.         }
  53.  
  54.         System.out.println(dp[0][n - 1]);
  55.     }
  56.     static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  57.     static StringTokenizer st;
  58.     static void readLine() throws IOException{
  59.         st = new StringTokenizer(in.readLine());
  60.     }
  61.     static int nextInt() {
  62.         return Integer.parseInt(st.nextToken());
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment