1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
/* vim: set expandtab tabstop=4 shiftwidth=4 : */
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Fast
{
static class Segment
{
private Point[] pts;
public Segment(Point ref, Point[] origin, int start, int n)
{
this.pts = new Point[n];
int i = 0;
int j = start;
boolean inserted = false;
while (i < (n - 1))
{
if (!inserted && (ref.compareTo(origin[j]) < 0))
{
pts[i++] = ref;
pts[i] = origin[j++];
inserted = true;
}
else
pts[i] = origin[j++];
i++;
}
if (!inserted)
pts[n - 1] = ref;
else
pts[n - 1] = origin[start + n - 2];
}
public boolean equals(Object other)
{
if (other == this) return true;
if (other == null) return false;
if (other.getClass() != this.getClass()) return false;
Segment s = (Segment) other;
if ((pts[0].compareTo(s.pts[0]) == 0)
|| (pts[pts.length - 1].compareTo(s.pts[s.pts.length - 1]) == 0))
return true;
return false;
}
public void draw()
{
pts[0].drawTo(pts[pts.length-1]);
}
public void print()
{
String out = "";
for (Point p : pts)
out += p+" -> ";
StdOut.println(out.substring(0, (out.length() - 4)));
}
}
static List<Segment> solve(Point[] pts, int N)
{
List<Segment> segments = new ArrayList<Segment>();
for (int i = 0; i < N - 1; i++)
{
int n = N - i - 1;
Point ref = pts[i];
Point[] others = new Point[n];
for (int j = 0, k = i + 1; j < n; j++, k++)
others[j] = pts[k];
Arrays.sort(others, ref.SLOPE_ORDER);
int start = -1;
double slope = Double.NEGATIVE_INFINITY;
for (int j = 0; j < n; j++)
{
double sl = ref.slopeTo(others[j]);
if (sl == Double.NEGATIVE_INFINITY)
continue;
if (slope != sl)
{
if ((start != -1) && ((j - start) > 2))
{
Segment seg = new Segment(ref, others,
start, (j - start + 1));
if (!segments.contains(seg))
segments.add(seg);
}
slope = sl;
start = j;
}
}
if ((n - start) > 2)
{
Segment seg = new Segment(ref, others, start, (n - start + 1));
if (!segments.contains(seg))
segments.add(seg);
}
}
return segments;
}
public static void main(String[] args)
{
In in = new In(args[0]);
int n = in.readInt();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
StdDraw.show(0);
Point[] pts = new Point[n];
for (int i = 0; i < n; i++)
{
pts[i] = new Point(in.readInt(), in.readInt());
pts[i].draw();
}
Arrays.sort(pts);
// Stopwatch w = new Stopwatch();
for (Segment sol : solve(pts, n))
{
sol.draw();
sol.print();
}
// StdOut.printf("Time: %f\n\n", w.elapsedTime());
StdDraw.show(0);
}
}
|