标题: | 近似算法求解旅行售货员问题 |
时 限: | 1000 ms |
内存限制: | 10000 K |
总时限: | 3000 ms |
描述: | 有一张城市地图,图中的顶点为城市,无向边代表两个城市间的连通关系,边上的权为在这两个城市之间修建高速公路的造价,研究后发现,这个地图有一个特点,即任一对城市都是连通的。现在的问题是,要修建若干高速公路把所有城市联系起来,问如何设计可使得工程的总造价最少。假定所有输入的根节点或者源为第一个城市或第一组数据。 |
输入: | n(城市数,1<=n<=100); e(边数); 以下e行,每行3个数i,j,wij,表示在城市i,j之间修建高速公路的造价。 |
输出: | n-1行,每行为两个城市的序号,表明这两个城市间建一条高速公路。 |
输入样例: | 5 8 1 2 2 1 3 12 1 4 10 2 3 8 2 5 9 3 4 6 3 5 3 4 5 7 |
输出样例: |
30 |
View Code
1 import java.util.Scanner; 2 3 public class Main { 4 static int n = 0; 5 static float[][] c = null; 6 static int mincost = 0; 7 8 public static void prim(int n, float[][] c) { 9 float[] lowcost = new float[n + 1]; 10 int[] closest = new int[n + 1]; 11 boolean[] s = new boolean[n + 1]; 12 13 s[1] = true; 14 15 for (int i = 2; i <= n; i++) { 16 lowcost[i] = c[1][i]; 17 closest[i] = 1; 18 s[i] = false; 19 } 20 21 int m = 1; 22 for (int i = 1; i < n; i++) { 23 float temp = Float.MAX_VALUE; 24 int j = 1; 25 for (int j2 = 2; j2 <= n; j2++) { 26 if ((!s[j2]) && (lowcost[j2] < temp)) { 27 temp = lowcost[j2]; 28 j = j2; 29 } 30 } 31 32 // System.out.println(closest[j]+ " "+j ); 33 mincost = mincost + (int) c[m][j]; 34 m = j; 35 36 if (i == n - 1) { 37 mincost = mincost + (int) c[j][1]; 38 } 39 s[j] = true; 40 41 for (int k = 2; k <= n; k++) { 42 if ((c[j][k] < lowcost[k]) && (!s[k])) { 43 lowcost[k] = c[j][k]; 44 closest[k] = j; 45 } 46 } 47 } 48 } 49 50 public static void main(String[] args) { 51 // TODO Auto-generated method stub 52 Scanner myscanner = new Scanner(System.in); 53 n = myscanner.nextInt(); 54 int e = 0; 55 e = myscanner.nextInt(); 56 c = new float[n + 1][n + 1]; 57 58 for (int i = 1; i <= n; i++) { 59 for (int j = 1; j <= n; j++) { 60 c[i][j] = Float.MAX_VALUE; 61 } 62 } 63 for (int i = 0; i < e; i++) { 64 int ix = myscanner.nextInt(); 65 int iy = myscanner.nextInt(); 66 int wij = myscanner.nextInt(); 67 //无向边 68 c[ix][iy] = wij; 69 c[iy][ix] = wij; 70 } 71 72 Main.prim(n, c); 73 74 System.out.println(mincost); 75 } 76 }