连通性问题

Connectivity Problem

本文关键字:问题 连通性      更新时间:2023-10-16

我需要知道我是否正确地阅读了这个问题。我在为面试做准备,我想我需要温习一下阅读理解能力。

问题说明:

假设给我们一个整数对序列,其中每个整数表示一个某种类型的对象,我们将对p-q解释为"p与q相连",我们假设关系"与"是可传递的:如果p与q相连,q与r相连,则p与r相连。我们的目标是编写一个程序从集合中过滤掉无关的对:当程序输入一对p-q时,只有当它所看到的对并不意味着p与q相连时,它才应该输出这对。如果前面的对确实意味着p与q相连,那么程序应该忽略p-q,并继续输入下一对。

我个人认为我没有在下面的代码中解决传递性部分,但是我有把事情弄得比需要的更复杂的倾向。我能从"c++中的算法"中得到这个问题的第二种解释吗?

/* 1 */ #include <iostream>
/* 2 */ #include <set>
/* 3 */ #include <algorithm>
/* 4 */ 
/* 5 */ using namespace std;
/* 6 */ 
/* 7 */ #define PAIRS 7
/* 8 */ 
/* 9 */ pair<int,int> pair_list[PAIRS] = {
/*10 */     pair<int,int>(0,2),
/*11 */     pair<int,int>(1,4),
/*12 */     pair<int,int>(2,5),
/*13 */     pair<int,int>(3,6),
/*14 */     pair<int,int>(0,4),
/*15 */     pair<int,int>(6,0),
/*16 */     pair<int,int>(2,0) 
/*17 */ };
/*18 */ 
/*19 */ void print( const pair<int,int> &out ) {
/*20 */     cout << "<" << out.first << ", " << out.second << ">" << endl;
/*21 */ }
/*22 */ 
/*23 */ bool contains( set<pair<int,int> > &_set, pair<int,int> &ordered_pair ) {
/*24 */     set<pair<int,int> >::iterator find = _set.find( ordered_pair );
/*25 */     bool ret = false;
/*26 */     if( find != _set.end( ) ) {
/*27 */         ret = true;
/*28 */     }
/*29 */     return ret;
/*30 */ }
/*31 */ 
/*32 */ int main( int argc, char **argv ) {
/*33 */     set<pair<int,int> > SET;
/*34 */     SET.clear( ); 
/*35 */     pair<int,int> *iter = &pair_list[0]; 
/*36 */     while( iter != &pair_list[PAIRS-1] ) {
/*37 */         if( !contains( SET,(*iter) ) ){
/*38 */                 SET.insert( (*iter) );
/*39 */         }
/*40 */         iter++;
/*41 */     }
/*42 */     
/*43 */     for_each( SET.begin( ), SET.end( ), print );
/*44 */     return ( 0 );
/*45 */ }

==================================================================================

更新:1

好吧,我想我想到了一个我喜欢的解决方案。花了我很长时间,这对面试来说很糟糕,但我还是做到了。

#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
#include <vector>
#include <iterator>
using namespace std;
void print_set( set<int>* _set ) {
    copy( _set->begin( ), _set->end( ), ostream_iterator<int>(cout, " ") );
    cout << endl;
}
void print_sets( set<set<int>*> _sets ) {
    for_each( _sets.begin( ), _sets.end( ), print_set );
}
void connectivity( queue<pair<int,int> > pairs ) {
    set<set<int>* > connected_items;
    while( pairs.size( ) ) {
        int first = pairs.front( ).first;
        int second = pairs.front( ).second;
        set<set<int>* >::iterator S=connected_items.begin( );
        bool found = false;
        bool dupli = false;
        set<int>* adj = new set<int>;
        while( S != connected_items.end( ) ) { //Go through all connected sets
            set<int>::iterator f=(*S)->find( first );
            set<int>::iterator s=(*S)->find( second );
            if( f!=(*S)->end( )&&s!=(*S)->end( ) ) {
                S++;
                dupli = true;
                continue;
            }
            if( f!=(*S)->end( )||s!=(*S)->end( ) ) {
                found = true;
                adj->insert( first );
                adj->insert( second );
                //copy( (*S)->begin( ), (*S)->end( ), ostream_iterator<int>( cout," ")  );
                set<int>::iterator num = (*S)->begin( );
                while( num != (*S)->end( ) ) {
                    adj->insert( (*num) );
                    num++;
                }
                connected_items.erase( S );
            }
            S++;
        }
        if( !found&&!dupli ) {
            set<int>* insert = new set<int>;
            connected_items.insert( insert );
            insert->insert( first );
            insert->insert( second );
        } else {
            connected_items.insert( adj );
        }
        pairs.pop( );
    }
    print_sets( connected_items );
}
int main( int argc, char **argv ) {
    queue<pair<int,int> > pairs;
    pairs.push( pair<int,int>( 1,2 ) );
    pairs.push( pair<int,int>( 2,3 ) );
    pairs.push( pair<int,int>( 2,4 ) );
    pairs.push( pair<int,int>( 2,5 ) );
    pairs.push( pair<int,int>( 6,7 ) );
    pairs.push( pair<int,int>( 6,8 ) );
    pairs.push( pair<int,int>( 6,9 ) );
    pairs.push( pair<int,int>( 9,10 ) );
    pairs.push( pair<int,int>( 11,12 ) );
    pairs.push( pair<int,int>( 12,13 ) );
    pairs.push( pair<int,int>( 14,15 ) );
    pairs.push( pair<int,int>( 2,12) );
    pairs.push( pair<int,int>( 2,1) );
    connectivity( pairs );
}

[mehoggan@desktop Connectivity]$ g++ -o connected -Wall connected.cpp; ./connected
6 7 8 9 10 
14 15 
1 2 3 4 5 11 12 13 

在输入对时,不检查传递性,也不检查路径是否正确输入。

如果你使用Boost的图形库,你可以创建一个无向图,并按深度优先搜索(DFS)顺序遍历它:

// Boost DFS example on an undirected graph.
// Create a sample graph, traverse its nodes
// in DFS order and print out their values.
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <iostream>
using namespace std;
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS> MyGraph;
typedef boost::graph_traits<MyGraph>::vertex_descriptor MyVertex;
class MyVisitor : public boost::default_dfs_visitor
{
public:
  void discover_vertex(MyVertex v, const MyGraph& g) const
  {
    cerr << v << endl;
    return;
  }
};
int main()
{
  MyGraph g;
  boost::add_edge(0, 1, g);
  boost::add_edge(0, 2, g);
  boost::add_edge(1, 2, g);
  boost::add_edge(1, 3, g);
  MyVisitor vis;
  boost::depth_first_search(g, boost::visitor(vis));
  return 0;
}

不对。

假设输入是(1,2),(2,3),(1,3)。那么输出应该是(1、2),(2、3),在您的代码(1、2),(2,3),(3,1)。

提示:您使用一个集合是正确的(实际上不止一个)。集合将包含整数,而不是整数对。集合中的整数都是相互连接的。

您实际上并没有测试您的函数。根据问题,函数应该拒绝冗余对。但是在你的数据集中没有冗余对。尝试将(0,5)插入到(2,5)之后的列表中。这应该被拒绝,因为我们已经看到了(0,2)和(2,5)。(我假设他们希望连通性是可交换的,而不仅仅是传递的,但是这个例子不需要它。)

一旦您这样做了,您将看到您的代码没有通过测试。你使用一个函数,contains(线索就在名字里),它检查一个特定的配对之前是否见过,而不是是否可以从之前见过的东西中推断出来。

编辑:
不,你没有修好它。阅读我上面写的;您仍然没有使用(0,5)这样的对进行测试,并且一旦您这样做了,您将看到您的代码仍然失败。

编辑:
对不起,是我的错。您的新代码可以工作。但是如果你不介意我这么说的话,你给自己增加了不必要的工作量,这是一些面试官会注意到的。看一下这个,进行比较:

void connectivity_adj(int first, int second,
                      set<set<int> > &connected_items){
  set<int> adj;
  adj.insert( first );
  adj.insert( second );
  for(set<set<int> >::iterator S=connected_items.begin( );
      S != connected_items.end( ); ++S){ //Go through all connected sets
          if( S->find(first) != S->end() || S->find( second ) != S->end( )){
        adj.insert(S->begin(), S->end());
        connected_items.erase( S );
      }
    }
  connected_items.insert( adj );
}

假设,如果a连接到b,那么b连接到a,那么这看起来应该是http://en.wikipedia.org/wiki/Disjoint-set_data_structure上的一个问题。请注意,带有路径压缩的最终改进版本比不太专门的集合结构更有效。

使用集合是一种很好的方法,但是第一个解决方案中的错误在于保持对的集合。这就是为什么它没有解决传递性需求。对1-2和2-1被视为两个不同的对象。

书中给出的解保存单个节点的集合(而不是节点对)。这允许您跟踪两个节点是否仅仅通过包含在同一集合中而连接,而不管它们的顺序如何。当给定两个节点作为输入时,如果它们不是同一集合的成员,则它们所属的集合被合并在一起。

这是基本的"快速查找"解决方案:

#include <iostream>
static const int N = 10000;
void quickFind() {
    int i, p, q, id[N];
    for (i = 0; i < N; i++) id[i] = i;
    while (std::cin >> p >> q) {
        int t = id[p];
        if (t == id[q]) continue;  // find
        for (i = 0; i < N; i++) {  // union
            if (id[i] == t) id[i] = id[q];
        }
        std::cout << "   " << p << " " << q << std::endl;
    }
}

通过初始化一组"set "在阵列id中,每个节点有一个唯一的值,从0到9999。"find"操作非常简单。如果两个节点(id数组的元素)的值相同,则它们在同一个集合中。"union"操作循环遍历数组并更新其中一个集合中的值,使它们成为另一个集合的成员,在下一次输入之前有效地将两个集合连接起来。