五大常用演算法——分支限界演算法詳解及經典例題
阿新 • • 發佈:2019-02-03
import static org.junit.Assert.*; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import javax.management.Query; import org.junit.Test; class Node{ private int curw, curv; private int units_i; private int[] route; Node(){ route = new int[110]; } public Node(int curw, int curv, int units_i, int[] route) { super(); this.curw = curw; this.curv = curv; this.units_i = units_i; this.route = route; } public int getCurw() { return curw; } public void setCurw(int curw) { this.curw = curw; } public int getCurv() { return curv; } public void setCurv(int curv) { this.curv = curv; } public int getUnits_i() { return units_i; } public void setUnits_i(int units_i) { this.units_i = units_i; } public int[] getRoute() { return route; } public void setRoute(int[] route) { this.route = route; } } public class 最小重量設計_分支限界法 { /* * 3 3 * 3 2 1 4 5 6 * 1 4 3 2 5 6 * 5 6 3 2 1 4 * 10 * * 答案是5 */ private static int w[][]; private static int c[][]; private static int n, m, cc; private static Scanner cin; private static Queue<Node>q; static{ cin = new Scanner(System.in); q = new LinkedList<Node>(); } public static void main(String[] args) { System.out.println("請輸入部件數目以及供貨商數量n和m:"); n = cin.nextInt(); m = cin.nextInt(); w = new int[n][m]; c = new int[n][m]; System.out.println("n行代表n個部件,每行輸入每個供貨商供應此部件的重量以及價格:"); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ w[i][j] = cin.nextInt(); c[i][j] = cin.nextInt(); } } System.out.println("請輸入不超過的價格p:"); cc = cin.nextInt(); q.clear(); int[] route = new int[110]; Node e = new Node(0, 0, -1, route); q.add(e); int ans = Integer.MAX_VALUE; while(!q.isEmpty()){ e = q.poll(); for(int j = 0; j < m; j++){ int i = e.getUnits_i() + 1; if(i >= n){ if(e.getCurv() <= cc){ if(ans > e.getCurw()){ ans = Math.min(ans, e.getCurw()); route = e.getRoute(); } } continue; } int curv = e.getCurv() + c[i][j]; int curw = e.getCurw() + w[i][j]; int[] lastroute = e.getRoute(); int[] curroute = new int[110]; for(int k = 0; k <= e.getUnits_i(); k++){ curroute[k] = lastroute[k]; } curroute[i] = j; q.add(new Node(curw, curv, i, curroute)); } } if(ans == Integer.MAX_VALUE){ System.out.println("不能找出總價格不超過 c的最小重量機器的方案"); }else{ System.out.println("滿足方案的最小重量是:" + ans); System.out.println("方案是:"); for(int j = 0; j < n; j++){ System.out.print(route[j] + " "); } } } }