算法轮船载重问题

默认分类 · 2023-04-19 · 38 人浏览
import java.util.Scanner;
public class Main {
    static int n;//集装箱数
    static int cw;//当前载重
    static int bestow;//最优载重
    static int r;//剩余集装箱重量
    static int c1;//第一艘轮船载重量
    static int c2;//第二艘轮船载重量
    static int[] x = new int[100];//当前解
    static int[] bests = new int[100];//最优解
    static int[] w = new int[100];//集装箱重量数组

    static void BackTrack(int i) {
        if (i > n) {
            if (cw > bestow) {
                if (n >= 0) System.arraycopy(x, 1, bests, 1, n);
                bestow = cw;
            }
            return;
        }
        r -= w[i];
        if (cw + w[i] <= c1) {
            cw += w[i];
            x[i] = 1;
            BackTrack(i + 1);
            x[i] = 0;
            cw -= w[i];
        }
        if (cw + r > bestow) {
            x[i] = 0;
            BackTrack(i + 1);
        }
        r += w[i];
    }

    static void Initialize() {
        bestow = 0;
        r = 0;
        cw = 0;
        for (int i = 1; i <= n; ++i) {
            r += w[i];
        }
    }

    static void InPut() {
        System.out.println("请输入集装箱个数:");
        Scanner yhy = new Scanner(System.in);
        n = yhy.nextInt();
        System.out.println("请输入两艘轮船最大载重量:");
        c1 = yhy.nextInt();
        c2 = yhy.nextInt();
        System.out.println("请输入每个集装箱重量:");
        for (int i = 1; i <= n; ++i) {
            w[i] = yhy.nextInt();
        }
    }

    static void OutPut() {
        int rw = 0;
        for (int i = 1; i <= n; ++i) {
            if (bests[i] == 0) {
                rw += w[i];
            }
        }
        if (rw > c2) {
            System.out.println("不能装入");
        } else {
            System.out.println("船1装入的货物为:");
            for (int i = 1; i <= n; ++i) {
                if (bests[i] == 1) {
                    System.out.println(i);
                }
            }
            System.out.println("船2装入的货物为:");
            for (int i = 1; i <= n; ++i) {
                if (bests[i] != 1) {
                    System.out.println(i);
                }
            }
        }
    }

    public static void main(String[] args) {
        InPut();
        Initialize();
        BackTrack(1);
        OutPut();
    }
}

Theme Jasmine by Kent Liao