题意理解
深搜加剪枝
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
public static class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.valueOf(nextToken());
}
public double nextDouble() {
return Double.valueOf(nextToken());
}
}
static double minLen = Double.MAX_VALUE;
static int N;
static double[][] distance;
static double[] xs;
static double[] ys;
static boolean[] visited;
public static void main(String[] args) {
FastScanner fs = new FastScanner();
N = fs.nextInt();
distance = new double[N + 1][N + 1];
xs = new double[N + 1];
ys = new double[N + 1];
visited = new boolean[N + 1];
xs[0] = 0;
ys[0] = 0;
for (int i = 1; i < N + 1; i++) {
xs[i] = fs.nextDouble();
ys[i] = fs.nextDouble();
}
for (int i = 0; i < N + 1; i++) {
for (int j = 0; j < N + 1; j++) {
double dx = xs[i] - xs[j];
double dy = ys[i] - ys[j];
double dSum = Math.pow(dx, 2) + Math.pow(dy, 2);
distance[i][j] = Math.sqrt(dSum);
}
}
dfs(0, 0, 0);
System.out.printf("%.2f", minLen);
}
static void dfs(int lastIndex, int step, double nowDistance) {
if (nowDistance > minLen) {
return;
}
if (step == N) {
minLen = nowDistance;
return;
}
for (int i = 1; i < N + 1; i++) {
if (!visited[i]) {
visited[i] = true;
dfs(i, step + 1, nowDistance + distance[lastIndex][i]);
visited[i] = false;
}
}
}
}