연습장에 기교 있는 검색 치즈 보급

6088 단어
제목 링크

제목의 뜻을 이해하다.


샅샅이 뒤져 가지를 치다

코드

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;
            }
        }
    }

}

좋은 웹페이지 즐겨찾기