p6p
6/22/2016 - 11:04 AM

Tsp.java


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Tsp{
 private int mg;
 private int cn;
 private double[][] adj;
 private int dt;
 private int[] gh;
 private double kk;
 private Random random;
 public Tsp(){
 }
 public Tsp(int n,int g){
	cn=n;
	mg=g;
 }
 private void init(String filename) throws IOException{
	double[] x;
	double[] y;
	String strbuff;
	BufferedReader data=new BufferedReader(new InputStreamReader(
		new FileInputStream(filename)));
	strbuff=data.readLine();
	cn=Integer.valueOf(strbuff.split(" ")[0]);
	adj=new double[cn][cn];
	x=new double[cn];
	y=new double[cn];
	for (int i=0; i<cn; i++){
	 strbuff=data.readLine();
	 String[] coll=strbuff.trim().split(" ");
	 x[i]=Double.valueOf(coll[1]);
	 y[i]=Double.valueOf(coll[2]);
	}
	for (int i=0; i<cn-1; i++){
	 adj[i][i]=0;
	 for (int j=i+1; j<cn; j++){
		double rij=Math
			.sqrt(((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])
				* (y[i]-y[j])));
		 adj[i][j]=rij;
		 adj[j][i]=adj[i][j];
	 }
	}
	adj[cn-1][cn-1]=0;
	gh=new int[cn];
	kk=Double.MAX_VALUE;
	dt=0;
	random=new Random(System.currentTimeMillis());
 }
 void initGroup(){
	int i,j;
	gh[0]=0;
	for (i=1; i<cn;)
	{
	 gh[i]=random.nextInt(65535)%cn;
	 for (j=0; j<i; j++){
		if (gh[i]==gh[j]){
		 break;
		}
	 }
	 if (j==i){
		i++;
	 }
	}
 }
 public double e(int[] chr){
	double len=0;
	for (int i=1; i<cn; i++){
	 len += adj[chr[i-1]][chr[i]];
	}
	len += adj[chr[cn-1]][chr[0]];
	return len;
 }
 public void y(int[] Gh,int T){
	int i,temp,tt=0;
	int ran1,ran2;
	double e;
	int[] tg=new int[cn];
	kk=e(Gh);
	for (tt=0; tt<T; tt++){
	 tg[0]=0;
	 for (i=1; i<cn; i++){
		tg[i]=Gh[i];
	 }
	 ran1=random.nextInt(65535)%cn;
	 ran2=random.nextInt(65535)%cn;
	 while (ran1==ran2||ran1==0||ran2==0){
		ran1=random.nextInt(65535)%cn;
		ran2=random.nextInt(65535)%cn;
	 }
	 temp=tg[ran1];
	 tg[ran1]=tg[ran2];
	 tg[ran2]=temp;
	 e=e(tg);
	 if (e<kk){
		dt=tt;
		kk=e;
		for (i=0; i<cn; i++){
		 Gh[i]=tg[i];
		}
	 }
	}
 }
 public void s(){
	initGroup();
	y(gh,mg);
	for (int i=0; i<cn; i++){
	 System.out.print(gh[i]+1+" ");
	}
	System.out.println();
	double result=0;
	for (int i=0; i<cn-1; ++i){
	 result += adj[gh[i]][gh[i+1]];
	}
	System.out.println();
	System.out.println(result);
 }
 public static void main(String[] args) throws IOException{
	Tsp Tsp=new Tsp(-1,500000);
	Tsp.init("TSP_ch130.txt");
	Tsp.s();
 }
}