How would you look at developing an algorithm for this hotel problem?

前端 未结 11 1992
误落风尘
误落风尘 2020-12-13 10:51

There is a problem I am working on for a programming course and I am having trouble developing an algorithm to suit the problem. Here it is:

You are

11条回答
  •  渐次进展
    2020-12-13 11:37

    If x is a marker number, ax is the mileage to that marker, and px is the minimum penalty to get to that marker, you can calculate pn for marker n if you know pm for all markers m before n.

    To calculate pn, find the minimum of pm + (200 - (an - am))^2 for all markers m where am < an and (200 - (an - am))^2 is less than your current best for pn (last part is optimization).

    For the starting marker 0, a0 = 0 and p0 = 0, for marker 1, p1 = (200 - a1)^2. With that starting information you can calculate p2, then p3 etc. up to pn.

    edit: Switched to Java code, using the example from OP's comment. Note that this does not have the optimization check described in second paragraph.

    public static void printPath(int path[], int i) {
        if (i == 0) return;
        printPath(path, path[i]);
        System.out.print(i + " ");
    }
    
    public static void main(String args[]) {
        int hotelList[] = {0, 200, 400, 600, 601};
        int penalties[] = {0, (int)Math.pow(200 - hotelList[1], 2), -1, -1, -1};
        int path[] = {0, 0, -1, -1, -1};
        for (int i = 2; i <= hotelList.length - 1; i++) {
            for(int j = 0; j < i; j++){
                int tempPen = (int)(penalties[j] + Math.pow(200 - (hotelList[i] - hotelList[j]), 2));
                if(penalties[i] == -1 || tempPen < penalties[i]){
                    penalties[i] = tempPen;
                    path[i] = j;
                }
            }
        }
        for (int i = 1; i < hotelList.length; i++) {
            System.out.print("Hotel: " + hotelList[i] + ", penalty: " + penalties[i] + ", path: ");
            printPath(path, i);
            System.out.println();
        }
    }
    

    Output is:

    Hotel: 200, penalty: 0, path: 1 
    Hotel: 400, penalty: 0, path: 1 2 
    Hotel: 600, penalty: 0, path: 1 2 3 
    Hotel: 601, penalty: 1, path: 1 2 4 
    

提交回复
热议问题