-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path最近对问题.cpp
More file actions
110 lines (106 loc) · 2.87 KB
/
最近对问题.cpp
File metadata and controls
110 lines (106 loc) · 2.87 KB
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
#include<bits/stdc++.h>
using namespace std;
const int n = 6;
struct point
{
int x, y;
};
double Closest(point S[ ], int low, int high);
double Distance(point a, point b);
int Partition(point r[ ], int first, int end);
void QuickSort(point r[ ], int first, int end);
int main()
{
point S[n] = {{1,1},{1,8},{2,6},{3,2},{4,1},{5,4}};
double minDist = Closest(S,0,n-1);
cout<<minDist<<endl;
return 0;
}
double Closest(point S[ ], int low, int high)
{
double d1, d2, d3, d;
int mid, i, j, index;
point P[n]; //存放P1和P2
if (high - low == 1)
return Distance(S[low], S[high]);
if (high - low == 2)
{
d1 = Distance(S[low], S[low+1]);
d2 = Distance(S[low+1], S[high]);
d3 = Distance(S[low], S[high]);
if ((d1 < d2) && (d1 < d3))
return d1;
else if (d2 < d3)
return d2;
else
return d3;
}
mid = (low + high)/2;
d1 = Closest(S, low, mid);
d2 = Closest(S, mid+1, high);
if (d1 <= d2)
d = d1;
else
d = d2;
index = 0;
for (i = mid; (i >= low) && (S[mid].x - S[i].x < d); i--)
P[index++] = S[i];
for (i = mid + 1; (i <= high) && (S[i].x - S[mid].x < d); i++)
P[index++] = S[i];
QuickSort(P, 0, index-1);
for (i = 0; i < index; i++)
{
for(j = i + 1; j < index; j++)
{
if (P[j].y - P[i].y >= d)
break;
else
{
d3 = Distance(P[i], P[j]);
if (d3 < d)
d = d3;
}
}
}
return d;
}
double Distance(point a, point b)
{
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
int Partition(point r[ ], int first, int end) //划分
{
int i = first, j=end; //初始化待划分区间
while (i < j)
{
while (i < j && r[i].y <= r[j].y)
j--; //右侧扫描
if (i < j)
{
point temp = r[i];
r[i] = r[j];
r[j] = temp; //将较小记录交换到前面
i++;
}
while (i < j && r[i].y <= r[j].y)
i++; //左侧扫描
if (i < j)
{
point temp = r[i];
r[i] = r[j];
r[j] = temp; //将较大记录交换到后面
j--;
}
}
return i; // 返回轴值记录的位置
}
void QuickSort(point r[ ], int first, int end) //快速排序
{
int pivot;
if (first < end)
{
pivot = Partition(r, first, end); //划分,pivot是轴值在序列中的位置
QuickSort(r, first, pivot-1); //求解子问题1,对左侧子序列进行快速排序
QuickSort(r, pivot+1, end); //求解子问题2,对右侧子序列进行快速排序
}
}