1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| public class LvXingShouhuoyuan { float[][] a;
public LvXingShouhuoyuan(float[][] a) { this.a = a; }
public static class HeapNode implements Comparable { float lcost; float cc; float rcost; int s; int[] x;
public HeapNode(float lc, float ccc, float rc, int ss, int[] xx) { lcost = lc; cc = ccc; s = ss; x = xx; }
public int compareTo(Object x) { float xlc = ((HeapNode) x).lcost; if (lcost < xlc) return -1; if (lcost == xlc) return 0; return 1; } }
public float bbTsp(int[] v) { int n = v.length - 1; LinkedList<HeapNode> heap = new LinkedList<HeapNode>(); float[] minOut = new float[n + 1]; float minSum = 0; for (int i = 1; i <= n; i++) { float min = Float.MAX_VALUE; for (int j = 1; j <= n; j++) { if (a[i][j] < Float.MAX_VALUE && a[i][j] < min) min = a[i][j]; } if (min == Float.MAX_VALUE) return Float.MAX_VALUE; minOut[i] = min; minSum += min; }
int[] x = new int[n]; for (int i = 0; i < n; i++) x[i] = i + 1; HeapNode enode = new HeapNode(0, 0, minSum, 0, x); float bestc = Float.MAX_VALUE;
while (enode != null && enode.s < n - 1) { x = enode.x; if (enode.s == n - 2) { if (a[x[n - 2]][x[n - 1]] != -1 && a[x[n - 1]][1] != -1 && enode.cc + a[x[n - 2]][x[n - 1]] + a[x[n - 1]][1] < bestc) { bestc = enode.cc + a[x[n - 2]][x[n - 1]] + a[x[n - 1]][1]; enode.cc = bestc; enode.lcost = bestc; enode.s++; heap.add(enode); Collections.sort(heap); } } else { for (int i = enode.s + 1; i < n; i++) { if (a[x[enode.s]][x[i]] != -1) { float cc = enode.cc + a[x[enode.s]][x[i]]; float rcost = enode.rcost = minOut[x[enode.s]]; float b = cc + rcost; if (b < bestc) { int[] xx = new int[n]; for (int j = 0; j < n; j++) xx[j] = x[j]; xx[enode.s + 1] = x[i]; xx[i] = x[enode.s + 1]; HeapNode node = new HeapNode(b, cc, rcost, enode.s + 1, xx); heap.add(node); Collections.sort(heap); } } }
}
enode = heap.poll(); } for (int i = 0; i < n; i++) v[i + 1] = enode.x[i]; return bestc; }
public static void main(String[] args) {
int n = 4; float[][] a = {{0, 0, 0, 0, 0,}, {0, -1, 30, 6, 4}, {0, 30, -1, 5, 10}, {0, 6, 5, -1, 20}, {0, 4, 10, 20, -1}}; LvXingShouhuoyuan b = new LvXingShouhuoyuan(a); int[] v = new int[n + 1]; System.out.println("输出:\n" + "最短回路长为:" + (int)(b.bbTsp(v))); System.out.print("最短回路为:"); for (int i = 1; i <= n; i++) { System.out.print(v[i] + " "); } } }
|