【发布时间】:2015-05-06 14:45:16
【问题描述】:
我当前的项目涉及根据点与 x-y 坐标平面原点的距离对点进行排序。它必须找到每个点到原点的距离,对距离进行排序,并输出创建距离的点,而不是距离。它只能使用桶排序和向量。我的排序工作正常,但我很难弄清楚如何确保距离矢量和点矢量保持对齐。 (距离 a B[0] 是从 c[0] 处的点创建的,即使该点最初不在 C[0] 处。)这是我目前的代码。
以标准用户输入为例:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2
首先,主要是从用户那里获取输入。点的每一半最初作为它自己的 double 进入向量 A,然后与另一半合并为向量 C 中的对。
int main(){
double number; int t = 0; pair<double,double> x;
while (cin >> number){
A.push_back(number); }
while (t < A.size()){
x = make_pair(A[t], A[t+1]); C.push_back(x); t += 2; }
int q = 0;
while (q < (C.size() - 1)){
findDistance(C[q].first, C[q].second);
q++;
}
然后,使用距离函数找到所有距离,其中结果存储在向量 B 中。这是函数。
void findDistance(double x = 0, double y = 0) {
double x2 = pow(x, 2);
double y2 = pow(y, 2);
double z = x2 + y2;
double final = sqrt(z);
B.push_back(final);
}
A bucketsort 组织所有的距离,将结果仍然存储在 B 中。
void bucketSort(vector<double> &arr)
{
int n = B.size();
vector<double> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
这就是问题所在。 B 已排序,但 C 保持其原始顺序。浏览和比较表之间的值以找到正确的顺序太昂贵了。 (其中一个参数是将运行时间保持为 O(n)。关于如何解决这个问题有什么想法吗?
这是我的完整代码:
vector<double> A;
vector<double> B;
vector<pair<double,double>> C;
void findDistance(double x = 0, double y = 0) {
double x2 = pow(x, 2);
double y2 = pow(y, 2);
double z = x2 + y2;
double final = sqrt(z);
B.push_back(final);
}
void bucketSort(vector<double> &arr)
{
int n = B.size();
vector<double> b[n];
for (int i=0; i<n; i++)
{
int bi = n*arr[i];
b[bi].push_back(arr[i]);
}
for (int i=0; i<n; i++)
sort(b[i].begin(), b[i].end());
int index = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < b[i].size(); j++){
arr[index++] = b[i][j]; }
}
}
int main(){
double number; int t = 0; pair<double,double> x;
while (cin >> number){
A.push_back(number); }
while (t < A.size()){
x = make_pair(A[t], A[t+1]); C.push_back(x); t += 2; }
cout << setprecision(5); cout << fixed;
int q = 0; double r = 0; double d = 0;
while (q < (C.size() - 1)){
findDistance(C[q].first, C[q].second);
q++;
}
bucketSort(B);
cout << showpos; cout << fixed;
//more cout here to show results
}
这是一个输入和输出示例: 输入:
0.2 0.38
0.6516 -0.1
-0.3 0.41
-0.38 0.2
输出:
-0.380000 +0.200000
+0.200000 +0.380000
-0.300000 +0.410000
+0.651600 -0.100000
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
由于计算距离是一个常数时间的运算,所以不妨省略距离向量,只根据距离对点向量进行排序。
-
如果要将它们排序在一起,请使用封装点和距离的结构。
标签: c++ vector c++14 bucket-sort