Cod sursa(job #2586878)

Utilizator emanuel.tertesTertes Emanuel emanuel.tertes Data 21 martie 2020 17:51:56
Problema Parantezare optima de matrici Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 1.91 kb
import java.util.*;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

class Main {
    static class Task {
        public final static String INPUT_FILE = "podm.in";
        public final static String OUTPUT_FILE = "podm.out";

        int n;
        int[] p;

        private final static long MAX = Long.MAX_VALUE;

        private void readInput() {
            try {
                Scanner sc = new Scanner(new File(INPUT_FILE));
                n = sc.nextInt();
                p = new int[n + 1];
                for (int i = 0; i <= n; i++) {
                    p[i] = sc.nextInt();
                }
                sc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private void writeOutput(long result) {
            try {
                PrintWriter pw = new PrintWriter(new File(OUTPUT_FILE));
                pw.printf("%d", result);
                pw.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private long getResult() {
            long[][] m = new long[n+1][n+1];
            long current_value;

            for(int l = 1; l <= n - 1; l++)
            	for (int i = 1; i <= n - l; i++){
            		int j = i + l;
            		m[i][j] = MAX;
            		for (int k = i; k <= j-1; k++) {

            			current_value = m[i][k] + m[k+1][j] + 1L*p[i-1]*p[k]*p[j];
          
            			if (current_value < m[i][j]) {
            				m[i][j] = current_value;
            			}			
            		}
            	}

            return m[1][n];
        }

        public void solve() {
            readInput();
            writeOutput(getResult());
        }
    }

    public static void main(String[] args) {
        new Task().solve();
    }
}