【问题标题】:Minimal distance in Manhattan metric曼哈顿度量中的最小距离
【发布时间】:2017-01-04 03:38:35
【问题描述】:

我试图在Manhattan metric (x,y) 中找到最小距离。我正在搜索有关此的信息。但我什么也没找到。

#include<bits/stdc++.h>
using namespace std;
#define st first
#define nd second

pair<int, int> pointsA[1000001];
pair<int, int> pointsB[1000001];

int main() {
    int n, t;
    unsigned long long dist;

    scanf("%d", &t);

    while(t-->0) {
        dist = 4000000000LL;
        scanf("%d", &n);

        for(int i = 0; i < n; i++) {
            scanf("%d%d", &pointsA[i].st, &pointsA[i].nd);
        }

        for(int i = 0; i < n; i++) {
            scanf("%d%d", &pointsB[i].st, &pointsB[i].nd);
        }

        for(int i = 0; i < n ;i++) {
            for(int j = 0; j < n ; j++) {
                if(abs(pointsA[i].st - pointsB[j].st) + abs(pointsA[i].nd - pointsB[j].nd) < dist) {
                    dist = abs(pointsA[i].st - pointsB[j].st) + abs(pointsA[i].nd - pointsB[j].nd);
                }
            }
            printf("%lld\n", dist);
        }
    }
}

我的代码在 O(n^2) 中工作,但太慢了。我不知道它是否有用,但是 pointsA 中的 y 总是 > 0 并且 pointsB 中的 y 总是

例如:

输入:

2
3
-2 2
1 3
3 1
0 -1
-1 -2
1 -2
1
1 1
-1 -1

输出:

5
4

【问题讨论】:

  • 首先请使用正确的缩进。
  • 看到你在while(t--&gt;0)中也发现了goes to zero operator
  • @Handus 你有 abs 具有相同的参数,可能是编译器优化这个,可能不是,如果你关心性能,为了简单起见,你应该将结果保存到变量。
  • 将其复杂度降低到 O(n^2) 以下并非易事。但是,您可以对其当前形式进行某些优化,例如不计算两次距离,或者例如如果 delta x 已经 > 当前最小距离,则不计算 y。如果当前 pointsA y > min dist 或 current pointsB y

标签: c++ algorithm optimization


【解决方案1】:

我的解决方案(注意,为简单起见,我不关心 manhattan_dist 中的溢出,因此它不适用于 unsigned long long):

#include <cstdlib>
#include <cstdio>
#include <cassert>
#include <vector>
#include <limits>
#include <algorithm>

typedef std::pair<int, int> Point;
typedef std::vector<std::pair<int, int> > PointsList;

static inline bool cmp_by_x(const Point &a, const Point &b)
{
    if (a.first < b.first) {
        return true;
    } else if (a.first > b.first) {
        return false;
    } else {
        return a.second < b.second;
    }
}

static inline bool cmp_by_y(const Point &a, const Point &b)
{
    if (a.second < b.second) {
        return true;
    } else if (a.second > b.second) {
        return false;
    } else {
        return a.first < b.first;
    }
}

static inline unsigned manhattan_dist(const Point &a, const Point &b)
{
    return std::abs(a.first - b.first) +
        std::abs(a.second - b.second);
}

int main()
{
    unsigned int n_iter = 0;
    if (scanf("%u", &n_iter) != 1) {
        std::abort();
    }
    for (unsigned i = 0; i < n_iter; ++i) {
        unsigned int N = 0;
        if (scanf("%u", &N) != 1) {
            std::abort();
        }
        if (N == 0) {
            continue;
        }
        PointsList pointsA(N);
        for (PointsList::iterator it = pointsA.begin(), endi = pointsA.end(); it != endi; ++it) {
            if (scanf("%d%d", &it->first, &it->second) != 2) {
                std::abort();
            }
            assert(it->second > 0);
        }
        PointsList pointsB(N);
        for (PointsList::iterator it = pointsB.begin(), endi = pointsB.end(); it != endi; ++it) {
            if (scanf("%d%d", &it->first, &it->second) != 2) {
                std::abort();
            }
            assert(it->second < 0);
        }

        std::sort(pointsA.begin(), pointsA.end(), cmp_by_y);
        std::sort(pointsB.begin(), pointsB.end(), cmp_by_y);
        const PointsList::const_iterator min_a_by_y = pointsA.begin();
        const PointsList::const_iterator max_b_by_y = (pointsB.rbegin() + 1).base();
        assert(*max_b_by_y == pointsB.back());

        unsigned dist = manhattan_dist(*min_a_by_y, *max_b_by_y);
        const unsigned diff_x = std::abs(min_a_by_y->first - max_b_by_y->first);
        const unsigned best_diff_y = dist - diff_x;

        const int max_y_for_a = max_b_by_y->second + dist;
        const int min_y_for_b = min_a_by_y->second - dist;
        PointsList::iterator it;
        for (it = pointsA.begin() + 1; it != pointsA.end() && it->second <= max_y_for_a; ++it) {
        }
        if (it != pointsA.end()) {
            pointsA.erase(it, pointsA.end());
        }

        PointsList::reverse_iterator rit;
        for (rit = pointsB.rbegin() + 1; rit != pointsB.rend() && rit->second >= min_y_for_b; ++rit) {
        }
        if (rit != pointsB.rend()) {
            pointsB.erase(pointsB.begin(), (rit + 1).base());
        }
        std::sort(pointsA.begin(), pointsA.end(), cmp_by_x);
        std::sort(pointsB.begin(), pointsB.end(), cmp_by_x);

        for (size_t j = 0; diff_x > 0 && j < pointsA.size(); ++j) {
            const Point &cur_a_point = pointsA[j];
            assert(max_y_for_a >= cur_a_point.second);
            const int diff_x = dist - best_diff_y;
            const int min_x = cur_a_point.first - diff_x + 1;
            const int max_x = cur_a_point.first + diff_x - 1;

            const Point search_term = std::make_pair(max_x, std::numeric_limits<int>::min());
            PointsList::const_iterator may_be_near_it = std::lower_bound(pointsB.begin(), pointsB.end(), search_term, cmp_by_x);

            for (PointsList::const_reverse_iterator rit(may_be_near_it); rit != pointsB.rend() && rit->first >= min_x; ++rit) {
                const unsigned cur_dist = manhattan_dist(cur_a_point, *rit);
                if (cur_dist < dist) {
                    dist = cur_dist;
                }
            }
        }
        printf("%u\n", dist);
    }
}

在我的机器上进行基准测试(Linux + i7 2.70 GHz + gcc -Ofast -march=native):

$ make bench
time ./test1 < data.txt  > test1_res

real    0m7.846s
user    0m7.820s
sys     0m0.000s
time ./test2 < data.txt  > test2_res

real    0m0.605s
user    0m0.590s
sys     0m0.010s

test1 是你的变体,test2 是我的。

【讨论】:

  • 您是否有机会发布输入数据的链接?
【解决方案2】:

您需要学习如何编写函数以及如何使用容器。以您当前的编码风格,不可能找到更好的解决方案。

问题是更好的解决方案是递归方法。按 X 坐标对点进行排序。现在递归地将集合分成两半,并确定每一半内的最近距离以及两半之间的最近距离。

最后一部分是有效的,因为两半都按 X 排序。将左半部分的最后一个值与右半部分的第一个值进行比较,可以得出良好的距离上限。

【讨论】:

  • 该算法已被证明可以为欧几里得距离产生正确的结果,但您确定它对于曼哈顿距离是正确的吗?
  • @JasonC:当然。该算法仅规定您需要考虑哪些点对。它不规定距离测量。两个指标的最坏情况实际上是相同的:一对的两个点具有相同的 Y 坐标,因此距离 d 只是 abs(x1-x2)
【解决方案3】:

所以有一个真的简单的优化可以让你减少大量的时间。

由于您声明集合 A 中的所有点都有 y > 0,并且集合 B 中的所有点都有 y mindist 的所有点和 B 中 y 永远不会比当前最近的对更近:

for(int i = 0; i < n ;i++) {
    if (pointsA[i].nd > dist)
        continue; // <- this is the big one
    for(int j = 0; j < n ; j++) {
        if (pointsB[j].nd < -dist)
            continue; // <- helps although not as much
        if(abs(pointsA[i].st - pointsB[j].st) + abs(pointsA[i].nd - pointsB[j].nd) < dist) {
            dist = abs(pointsA[i].st - pointsB[j].st) + abs(pointsA[i].nd - pointsB[j].nd);
        }
    }
    printf("%lld\n", dist);
}

对于每组 40000 点的测试,在我的机器上使用 gcc 和 -O2 这将时间从 8.2 秒减少到大约 0.01 秒(并产生正确的结果)! (在 Windows 上使用QueryPerformanceCounter 测量)。

不会太破旧。

Fwiw,计算你的距离两次其实没什么大不了的。首先,“第二次”计算实际上并不经常发生,只有在找到更近的距离时才会发生。

其次,由于我无法解释的原因,将它存储在一个变量中并且只计算一次实际上始终一致地似乎增加了大约 20% 的总运行时间,将它从平均 8.2 秒提高到大约 10.5 秒对于上面的集合。

我想说的是,在不显着改变算法的情况下,根据您对 Y 值的假设丢弃分数是迄今为止您可以获得的最大收益。

您可以通过预先对 A 和 B 进行排序来进一步利用这一点套。

【讨论】:

    【解决方案4】:

    保留 A 组和 B 组中的候选人列表,最初包含整个输入。对 y 中最近的对取 A 的 min y 和 max y B,计算曼哈顿距离,并从候选列表中消除任何 y 大于上限的值。这可能会削减输入或者它可能基本上没有效果,但它是 O(N) 并且是一个便宜的第一步。

    现在对 x 和 y 中的剩余候选进行排序。这为您提供了 y 中的单独列表和 x 中的混合列表,并且是 O(N log N),其中 N 已通过第一步被削减,希望但不一定。 对于每个点,现在计算它在 y 中的最近邻居(微不足道)和在 x 中最近的邻居(有点困难),然后计算其最小可能的曼哈顿距离,假设 x 中最近的也是 y 中最近的。从候选列表中消除任何超出您界限的点。现在再次排序,尽可能最小。那是另一个 N log N 操作。 现在从你的最佳候选者开始,找到它真正的最小距离,通过尝试 x 或 y 中任一方向上的最近点,并在 delta x 或 delta y 超过迄今为止最好的点,或者 delta x 或 delta y 超过时终止你的最大界限。如果您有比当前候选对更好的候选对,请清除候选列表中的所有内容,并尽可能降低最小值。如果最佳候选点没有形成候选对的一半,则只需清除该点。

    当您清除了一定数量的候选人后,重新计算列表。我不确定使用的最佳价值是什么,当然,如果你得到最差的候选人,你必须这样做,然后以最好的方式重新开始。也许使用 50%。

    最终你只剩下一对候选对。我不太确定分析是什么——最坏的情况,我想你在每次测试中只淘汰了几个候选人。但是对于大多数输入,您应该很快将候选列表降低到一个较小的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      相关资源
      最近更新 更多