凸包graham扫描法

import java.util.*;

public class ConvexHull {

	private static Point[] p;
	private static Point p1;
	private static Point[] CH;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		p = new Point[N];
		int firstIndex = 0;
		double firstX = sc.nextDouble();
		double firstY = sc.nextDouble();
		p[0] = new Point(firstX, firstY);
		for (int i = 1; i < N; i++) {
			double x = sc.nextDouble();
			double y = sc.nextDouble();
			p[i] = new Point(x, y);
			if (y < firstY || (y == firstY && x < firstX)) {
				firstY = y;
				firstX = x;
				firstIndex = i;
			}
		}
		Point temp = p[0];
		p[0] = p[firstIndex];
		p[firstIndex] = temp;
		p1 = p[0];
		Arrays.sort(p, 1, p.length, new MyComparator());
		grahamScan();
	}

	private static void grahamScan() {
		CH = new Point[p.length];
		CH[0] = p[0];
		CH[1] = p[1];
		CH[2] = p[2];
		int top = 2;
		for (int k = 3; k < p.length; ++k) {
			while (crossProduct(CH[top - 1], CH[top], p[k]) <= 0) {
				if (top-- == 0)// 防止所有点共线
					break;
			}
			CH[++top] = p[k];
		}
		for (int i = 0; i <= top; i++) {
			System.out.println(CH[i].x + "\t" + CH[i].y);
		}
	}

	private static class MyComparator implements Comparator<Point> {
		public int compare(Point o1, Point o2) {
			double cross = crossProduct(p1, o1, o2);
			if (cross < 0.0000001 && cross > -0.0000001) {
				return (o1.y - o2.y) > 0 ? 1 : -1;
			}
			return cross > 0 ? -1 : 1;
		}
	}

	public static double crossProduct(Point pp, Point o1, Point o2) {
		return (o1.x - pp.x) * (o2.y - pp.y) - (o2.x - pp.x) * (o1.y - pp.y);
	}

	private static class Point {
		public Point(double x2, double y2) {
			this.x = x2;
			this.y = y2;
		}

		double x, y;
	}
}


测试数据:

10
1 -2
1 2
5 3
4 5
2 -4
6 -6
7 0
10 -3
9 4
8 -1


6.0 -6.0
10.0 -3.0
9.0 4.0
4.0 5.0
1.0 2.0
1.0 -2.0
2.0 -4.0

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值