Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- public class ConvexHullProblem {
- static int direction(Point a, Point b, Point c) {
- return (b.x - a.x) * (c.y - b.y) - (c.x - b.x) * (b.y - a.y);
- }
- public static void main(String[] args) throws IOException{
- readLine();
- int n = nextInt();
- Point[] points = new Point[n];
- for(int i = 0; i < n; i ++) {
- readLine();
- points[i] = new Point(nextInt(), nextInt());
- }
- Arrays.sort(points);
- Stack<Point> top = new Stack<Point>();
- for(int i = 0; i < n; i ++) {
- Point next = points[i];
- boolean cw = false;
- while(top.size() > 1 && ! cw) {
- Point b = top.pop();
- Point a = top.peek();
- if(direction(a, b, next) < 0) {
- cw = true;
- top.push(b);
- }
- }
- top.push(next);
- }
- Stack<Point> bottom = new Stack<Point>();
- for(int i = n - 1; i >= 0; i --) {
- Point next = points[i];
- boolean cw = false;
- while(bottom.size() > 1 && ! cw) {
- Point b = bottom.pop();
- Point a = bottom.peek();
- if(direction(a, b, next) < 0) {
- cw = true;
- bottom.push(b);
- }
- }
- bottom.push(next);
- }
- bottom.pop();
- bottom.remove(0);
- top.addAll(bottom);
- System.out.println(top);
- }
- static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- static StringTokenizer st;
- static void readLine() throws IOException{
- st = new StringTokenizer(in.readLine());
- }
- static int nextInt() {
- return Integer.parseInt(st.nextToken());
- }
- static class Point implements Comparable<Point>{
- int x, y;
- Point(int x, int y){
- this.x = x;
- this.y = y;
- }
- @Override
- public int compareTo(Point o) {
- if(this.x == o.x) {
- return this.y - o.y;
- }
- return this.x - o.x;
- }
- public String toString(){
- return "(" + x + ", " + y + ")";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment