12

我知道 STL 有set_difference,但我只需要知道 2 sets 是否不相交。我已经分析了我的代码,这大大降低了我的应用程序的速度。有没有一种简单的方法可以查看 2 组是否不相交,或者我是否只需要滚动自己的代码?

编辑:我也试过set_intersection,但花了同样的时间......

4

5 回答 5

17

修改了 hjhill 的代码,通过去掉 count() 调用,将复杂性降低了 O(log n) 倍。

template<class Set1, class Set2> 
bool is_disjoint(const Set1 &set1, const Set2 &set2)
{
    if(set1.empty() || set2.empty()) return true;

    typename Set1::const_iterator 
        it1 = set1.begin(), 
        it1End = set1.end();
    typename Set2::const_iterator 
        it2 = set2.begin(), 
        it2End = set2.end();

    if(*it1 > *set2.rbegin() || *it2 > *set1.rbegin()) return true;

    while(it1 != it1End && it2 != it2End)
    {
        if(*it1 == *it2) return false;
        if(*it1 < *it2) { it1++; }
        else { it2++; }
    }

    return true;
}

我现在已经编译并测试了这段代码,所以它应该很好。

于 2009-12-26T20:13:53.160 回答
5

由于std::set是一个排序容器,您可以比较设置的边界以查看它们是否可能相交,如果是,则执行昂贵的 STL 操作。

编辑:

这是蛤蜊钓鱼变得严肃的地方......

到目前为止发布的所有代码都试图重新实现<algorithm>中已经存在的内容。这是要点set_intersection


  template<typename _InputIterator1, typename _InputIterator2,
           typename _OutputIterator>
    _OutputIterator
    set_intersection(_InputIterator1 __first1, _InputIterator1 __last1,
                     _InputIterator2 __first2, _InputIterator2 __last2,
                     _OutputIterator __result)
    {
      while (__first1 != __last1 && __first2 != __last2)
        if (*__first1 < *__first2)
          ++__first1;
        else if (*__first2 < *__first1)
          ++__first2;
        else
          {
            *__result = *__first1;
            ++__first1;
            ++__first2;
            ++__result;
          }
      return __result;
    }

除了分配给输出迭代器之外已经非常优化了,这对于仅查找两个集合是否联合的事实是不必要的。这可以用于翻转标志,如下所示:


  /// fake insert container
  template <typename T> struct intersect_flag
  {       
    typedef int iterator;
    typedef typename T::const_reference const_reference;

    bool flag_; // tells whether given sets intersect

    intersect_flag() : flag_( false ) {}

    iterator insert( iterator, const_reference )
    {       
      flag_ = true; return 0;
    }
  };

  // ...
  typedef std::set<std::string> my_set;

  my_set s0, s1;
  intersect_flag<my_set> intf;

  // ...        
  std::set_intersection( s0.begin(), s0.end(),
    s1.begin(), s1.end(), std::inserter( intf, 0 ));

  if ( intf.flag_ ) // sets intersect
  {
    // ...

这避免了从原始集合中复制对象,并允许您重用 STL 算法。

于 2009-12-26T19:46:04.883 回答
3

您可以使用set_intersection并测试结果集是否为空,但我不知道这是否更快。

最佳实现将停止测试,并return false在找到第一个相等元素后立即停止。不过,我不知道有任何现成的解决方案

template<class Set1, class Set2> 
bool is_disjoint(const Set1 &set1, const Set2 &set2)
{
    Set1::const_iterator it, itEnd = set1.end();
    for (it = set1.begin(); it != itEnd; ++it)
        if (set2.count(*it))
            return false;

    return true;
}

不太复杂,应该很好地完成工作。

编辑:如果你想要 O(n) 性能,请使用稍微不那么紧凑的

template<class Set1, class Set2> 
bool is_disjoint(const Set1 &set1, const Set2 &set2)
{
    Set1::const_iterator it1 = set1.begin(), it1End = set1.end();
    if (it1 == it1End)
        return true; // first set empty => sets are disjoint

    Set2::const_iterator it2 = set2.begin(), it2End = set2.end();
    if (it2 == it2End)
        return true; // second set empty => sets are disjoint

    // first optimization: check if sets overlap (with O(1) complexity)
    Set1::const_iterator it1Last = it1End;
    if (*--it1Last < *it2)
        return true; // all elements in set1 < all elements in set2
    Set2::const_iterator it2Last = it2End;
    if (*--it2Last < *it1)
        return true; // all elements in set2 < all elements in set1

    // second optimization: begin scanning at the intersection point of the sets    
    it1 = set1.lower_bound(*it2);
    if (it1 == it1End)
        return true;
    it2 = set2.lower_bound(*it1);
    if (it2 == it2End)
        return true;

    // scan the (remaining part of the) sets (with O(n) complexity) 
    for(;;)
    {
        if (*it1 < *it2)
        {
            if (++it1 == it1End)
                return true;
        } 
        else if (*it2 < *it1)
        {
            if (++it2 == it2End)
                return true;
        }
        else
            return false;
    }
}

(进一步修改了Graphics Noob的修改,仅使用运算符<)

于 2009-12-26T19:44:09.897 回答
2

通过使用两个集合都已排序的事实,可以获得 O(log(n))。只需使用std::lower_bound而不是将迭代器移动一个。

enum Ordering { EQ = 0, LT = -1, GT = 1 };

template <typename A, typename B>
Ordering compare(const A &a, const B &b)
{
    return
        a == b ? EQ :
        a < b ? LT : GT;
}

template <typename SetA, typename SetB>
bool is_disjoint(const SetA &a, const SetB &b)
{
    auto it_a = a.begin();
    auto it_b = b.begin();
    while (it_a != a.end() && it_b != b.end())
    {
        switch (compare(*it_a, *it_b))
        {
        case EQ:
            return false;
        case LT:
            it_a = std::lower_bound(++it_a, a.end(), *it_b);
            break;
        case GT:
            it_b = std::lower_bound(++it_b, b.end(), *it_a);
            break;
        }
    }
    return true;
}
于 2015-03-18T13:28:51.867 回答
1

使用std::set_intersection,看看输出是否为空。您可以先检查两个集合的范围(开始和结束迭代器覆盖的区域)是否重叠,但我怀疑 set_intersection 可能已经这样做了。

这些都是 O(n) 操作,is_disjoint 也是如此。如果 O(n) 是不可接受的,则必须构建一些侧存储以在添加/删除元素时“跟踪”集合的不相交性。在这里,您将在插入时支付开销(通过为每个集合修改更新您的“isdisjoint”结构),但 is_disjoint 可以廉价地实现。这可能是也可能不是一个很好的权衡。

于 2009-12-26T19:44:39.553 回答