(UVA) Flight Planner - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=655&page=show_problem&problem=1278

The solution below used Dynamic Programming to solve this problem.


import java.io.*;
import java.util.*;

class Main {
    public int distanceToFly;
    public int[][] windstrength;
    public int[][] state;
   
    public int rec(int currAltitude, int currColumn) {
        if (currAltitude >= 10 || currColumn > distanceToFly/100 || currAltitude < 0 || currColumn < 0) {
            return Integer.MAX_VALUE/2; // invalid
        }
       
        if (currAltitude == 9 && currColumn == distanceToFly/100) {
            return 0; // I didnt waste any fuel (base)
        }
       
        if (state[currAltitude][currColumn] != -1) {
            return state[currAltitude][currColumn];
        }
       
        int climb = rec(currAltitude-1, currColumn+1)+60-windstrength[currAltitude][currColumn];
        int hold = rec(currAltitude, currColumn+1)+30-windstrength[currAltitude][currColumn];
        int sink = rec(currAltitude+1, currColumn+1)+20-windstrength[currAltitude][currColumn];
       
        int minClimbHold = Math.min(climb, hold);
        int minClimbHoldSink = Math.min(minClimbHold, sink);
        state[currAltitude][currColumn] = minClimbHoldSink;
        return state[currAltitude][currColumn];
    }
   
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int numTests = sc.nextInt();
        for (int test = 0; test < numTests; test++) {
            distanceToFly = sc.nextInt();
           
            windstrength = new int[10][distanceToFly/100+1];
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < distanceToFly/100; j++) {
                    windstrength[i][j] = sc.nextInt();
                }
                windstrength[i][distanceToFly/100] = 0;
            }
           
            state = new int[10][distanceToFly/100+1];
            for (int i = 0; i < 10; i++) {
                for (int j = 0; j < distanceToFly/100+1; j++) {
                    state[i][j] = -1;
                }
            }
           
            bw.write(rec(9, 0)+"\n\n");
        }
                                              
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução