AtCoder Beginner Contest 022 D: Big Bang (幾何・凸包)

問題

abc022.contest.atcoder.jp

解法

www.slideshare.net

外側の点を結んで、全ての点が内部か線上にあるような多角形を作る。(凸包というらしい)この多角形の周囲の長さもP倍されているので、1回目の外周と2回目の外周を出して割れば良い。

コード

import java.io.IOException;
import java.util.ArrayList;

public class Main {

	public static void main(String[] args) {
		int N = nextInt();

		int[] AX = new int[N];
		int[] AY = new int[N];
		int[] BX = new int[N];
		int[] BY = new int[N];
		for (int i = 0; i < N; i++) {
			AX[i] = nextInt();
			AY[i] = nextInt();
		}
		for (int i = 0; i < N; i++) {
			BX[i] = nextInt();
			BY[i] = nextInt();
		}

		double pA = getTotsu(AX, AY);
		double pB = getTotsu(BX, BY);
		System.out.println(pB / pA);

	}

	static double getTotsu(int[] x, int[] y) {
		int N = x.length;
		ArrayList<Integer> list = new ArrayList<>();
		int start = 0;
		// x座標のもっとも大きい点を始点にする
		for (int i = 1; i < N; i++) {
			if (x[start] < x[i])
				start = i;
		}
		boolean[] used = new boolean[N];
		used[start] = true;
		list.add(start);

		// Y軸の正の向きの単位ベクトル
		double[] prevDir = new double[2];
		prevDir[0] = 0.0;
		prevDir[1] = 1.0;

		while (true) {
			int from = list.get(list.size() - 1);
			double max = -2;
			int next = -1;

			for (int to = 0; to < N; to++) {
				// 前のベクトルに対して最も内積が大きくなるように次の点を探す
				// そうすると、曲がり角を最大にすることが出来る
				double[] toDir = direction(x, y, from, to);
				double pro = product(prevDir, toDir);
				if (max < pro) {
					max = pro;
					next = to;
				}
			}

			prevDir = direction(x, y, from, next);
			list.add(next);
			if (used[next]) {
				break;
			}
			used[next] = true;
		}

		int last = list.get(list.size() - 1);
		while (list.get(0) != last) {
			list.remove(0);
		}

		double ans = 0;
		for (int i = 1; i < list.size(); i++) {
			int a = list.get(i - 1);
			int b = list.get(i);

			ans += Math.sqrt(Math.pow(x[a] - x[b], 2) + Math.pow(y[a] - y[b], 2));
		}
		return ans;
	}

	static double[] direction(int[] X, int[] Y, int from, int to) {
		// fromからtoへの単位ベクトルを返す
		double dx = X[to] - X[from];
		double dy = Y[to] - Y[from];
		return new double[] { dx / Math.sqrt(dx * dx + dy * dy), dy / Math.sqrt(dx * dx + dy * dy) };
	}

	static double product(double[] a, double[] b) {
		// ベクトル内積を返す
		return a[0] * b[0] + a[1] * b[1];
	}

	static int nextInt() {
		int c;
		try {
			c = System.in.read();
			while (c != '-' && (c < '0' || c > '9'))
				c = System.in.read();
			if (c == '-')
				return -nextInt();
			int res = 0;
			while (c >= '0' && c <= '9') {
				res = res * 10 + c - '0';
				c = System.in.read();
			}
			return res;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1;
	}

}

平行移動とか回転とかしなくて良いということに全く気付けなかったあああああああああああああああああああ