编译期判断有向图中是否有环

来源:互联网 发布:企业网站怎样优化 编辑:程序博客网 时间:2024/04/20 13:48
C++ template,本文纯是玩技巧的,没啥实用性
核心思想是利用继承关系保存图,同时利用template查找节点,代码很短,不需要多说,直接上代码,该代码GCC 4.6.1与VS2010下无压力通过, 其他平台求验证~

#include <iostream>
template <int sn, int tn>
struct Edge
{
  enum{
    start = sn,
    end = tn
  };
};

template <typename Ty_, typename PTy_ = void, int s = 0>
class Graph
{
public :
  enum{
    edge_end = -1,
    edge_start = -2
  };
  enum{
    has_cycle = false
  };
  enum {
    search_end = 0
  };
};

template<int sn, int tn, typename PTy_, int s>
class Graph<Edge<sn,tn>, PTy_, s>
{
  public :
    enum{
    edge_start = sn,
    edge_end = tn
  };
  enum{
    has_cycle = sn == tn ? true : false
  };
    enum {
    search_end = edge_start ==s ? edge_end : 0
  };
};

template <int sn, int tn, typename Tx_, typename Ty_, int s>
class Graph<Edge<sn, tn>, Graph<Tx_, Ty_> , s> : public Graph<Tx_, Ty_, tn>
{
public:
  enum{
    edge_start = sn,
    edge_end = tn
  };
  enum {
    search_end = Graph<Tx_, Ty_, tn>::search_end==0 ? tn : Graph<Tx_, Ty_, tn>::search_end 
  };
  enum{
    has_cycle = edge_start == search_end ? true : Graph<Tx_, Ty_, tn>::has_cycle
  };
};

typedef Edge<1, 2> e1;
typedef Edge<2, 3> e2;
typedef Edge<3, 1> e3;
typedef Edge<2, 1> e4;
typedef Edge<3, 2> e5;

typedef Graph<e1> g1;
typedef Graph<e2, g1> g2;

typedef Graph<e3, g2> g3;

typedef Graph<e4, g1> g4;

typedef Graph<e5, g2> g5;

int main(int argc, char **argv) {
  std::cout<<g1::has_cycle<<std::endl;
  std::cout<<g2::has_cycle<<std::endl;
  std::cout<<g3::has_cycle<<std::endl;
  std::cout<<g4::has_cycle<<std::endl;
  std::cout<<g5::has_cycle<<std::endl;
    return 0;
}
原创粉丝点击