# TSP问题

2
0 52
52 0
2
0 319
430 319
0 96
430 96
0

## 样例输出

104
845
TSP问题:

从店家开始,尝试每种可能的送法,(试完后恢复局面)
送完后把局面交给下一状态
a[i][j]表示从i送到j

public class Problem_cid_1168_pid_10 {
static int  min=5000;
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int t = cin.nextInt();
while (t-->0) {
int  num=cin.nextInt();
int a[][]=new  int[num+1][num+1];//距离
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j]=cin.nextInt();
}
}
int currentsum=0;
boolean[][] b=new boolean[num+1][num+1];
for (int i = 0; i < b.length; i++)b[i][i]=true;
min=5000;
boolean  []hasdeal=new boolean[num+1];
f(num,a,currentsum,1, currentsum,b,0,hasdeal);
System.out.println(min);
}
}
/**
*@param num:外卖份数
*@param a:距离矩阵
*@param currentsum:当前计算的距离总合
*@param y:下一份外卖在哪
*@param dealnum:当前送出的外卖数
*@param b:标记外卖是否已经送出
*@param x:上一份外卖在哪
*/
private static void f(int num,int[][] a, int currentsum,int y,int dealnum,boolean [][]b,int x,boolean [] hasdeal) {

if (dealnum==num) {
int ans=currentsum+a[y][0];
//		System.out.println("dealnum="+dealnum+"   currentsum="+currentsum+"   a["+x+"][0]="+a[x][0]+"   ans="+ans);
min=Math.min(ans, min);
return ;
}
if (currentsum>min)	return ;
for (int i = 1; i <a[0].length ; i++) {//从这份外卖开始，尝试送出
if (i!=x&&b[x][i]==false&&hasdeal[i]==false) {
b[i][x]=b[x][i]=true;
hasdeal[i]=true;
f(num,a, currentsum+a[x][i],i, dealnum+1, b, i,hasdeal);
hasdeal[i]=false;
b[i][x]=b[x][i]=false;
}
}
}

}

0 个人打赏

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试