算法代考作业第二题:某售货员要到若干城市去推销商品,已知各城市之间的路程,他要选定一条从驻地出发,经过每个城市一遍,最后回到住地的路线,使总的路程最短。假定旅行商的起始点一定为1号城市
Input
第1行有两个正整数n和m,1<=n<=100, 1<=m<=1000,分别代表图中城市个数和城市间路的个数。
第2行至第m+1行分别有3个整数cityA,cityB ,distance表示图中的一条路,其两端城市编号是cityA和cityB,编号从1开始,distance代表这两个城市间的距离。
Output
第一行输出一个正整数表示旅行商经过的最短路径。
接下来一行输出多个正整数,表示旅行商经过的城市次序,起始点与终点一致。
测试样例:
Sample Input
4 6
1 2 30
1 3 6
1 4 4
2 4 10
2 3 5
3 4 20
Sample Output
25
1 3 2 4 1
import java.util.*;
public class Main {
public static int minDistance = 1000000; //存放最终的最小值,假定最优路径的最小值一定小于 1000000,1000000充当一个无穷大量
public static int nowDistance=0;
public static ArrayList<Integer> bestList = new ArrayList<Integer>(); //存放最优的路径经过城市顺序
public static ArrayList<Integer> tmpList = new ArrayList<Integer>(); //暂存递归过程中的临时经过城市顺序
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt(); //n存放城市的数目,m用来存放城市间道路的数量
int[][] citys = new int[n][n]; //存放两城市之间的距离,若城市无连接则距离为零
for(int i=0;i<m;i++) {
int cityA = sc.nextInt(), cityB = sc.nextInt(), distance = sc.nextInt();
citys[cityA-1][cityB-1] = distance;
citys[cityB-1][cityA-1] = distance;
}
tmpList.add(0);
Recursion(n, citys);
System.out.println(minDistance);
int[] bestCities = new int[bestList.size()]; //存放最终最优结果的数组
for(int i=0;i<bestList.size();i++) {
bestCities[i] = bestList.get(i)+1;
}
for(int i=0;i<bestList.size();i++)
System.out.print(bestCities[i]+" ");
}
static void Recursion(int n, int[][] citys) {
int lastestCity = tmpList.get(tmpList.size()-1); //最近到达的一个城市
if(tmpList.size()<n && nowDistance<minDistance) { //遍历过程
for(int i=1;i<n;i++) {
if(citys[lastestCity][i]!=0 && tmpList.indexOf(i)==-1) {
nowDistance += citys[lastestCity][i];
tmpList.add(i);
Recursion(n, citys);
nowDistance -= citys[lastestCity][i];
tmpList.remove(tmpList.size()-1);
}
}
}
else { //最后回到起点
if(citys[lastestCity][0]!=0) {
nowDistance += citys[lastestCity][0];
tmpList.add(0);
if(nowDistance<minDistance) {
minDistance = nowDistance;
bestList = (ArrayList<Integer>) tmpList.clone();
}
tmpList.remove(tmpList.size()-1);
nowDistance -= citys[lastestCity][0];
}
}
}
}
算法效率好像相对较低,没找太多例题,只测试了样例一组结果,且暂时没有改进。
菜鸟上路,大佬勿喷,欢迎指正