• dataStructure@ Check if a directed graph has cycles


     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<limits>
     5 #include<vector>
     6 using namespace std;
     7 const int maxn = 10;
     8 struct edge{
     9     int to, cost;
    10     edge(int t){
    11         this->to = t; this->cost = 0;
    12     }
    13 };
    14 void addEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
    15     edgelist.push_back(edge(to));
    16     G[from].push_back(edgelist.size()-1);
    17 }
    18 void addDoubleEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
    19     addEdge(edgelist,G,from,to);
    20     addEdge(edgelist,G,to,from);
    21 }
    22 bool isCyclic(vector<edge> edgelist, vector<vector<int> > G,vector<bool> vis, vector<bool> RecStack, int v){
    23     for(int i=0;i<G[v].size();++i){
    24         edge e = edgelist[G[v][i]];
    25         if(RecStack[e.to]) return true;
    26         if(!vis[e.to]){
    27             vis[e.to] = true; RecStack[e.to] = true;
    28             if(isCyclic(edgelist,G,vis,RecStack,e.to)) return true;
    29             RecStack[e.to] = false;
    30         }
    31     }
    32     return false;
    33 }
    34 void buildMap(vector<edge> &edgelist, vector<vector<int> > &G){
    35     addEdge(edgelist,G,0,1);
    36     addEdge(edgelist,G,0,2);
    37     addEdge(edgelist,G,2,0);
    38     addEdge(edgelist,G,1,2);
    39     addEdge(edgelist,G,2,3);
    40     addEdge(edgelist,G,3,3);
    41 }
    42 int main(){
    43     vector<edge> edgelist;
    44     vector<vector<int> > G(maxn);
    45     vector<bool> vis(maxn);
    46     vector<bool> RecStack(maxn);
    47     
    48     buildMap(edgelist,G);
    49     
    50     for(int i=0;i<vis.size();++i) vis[i]=false;
    51     for(int i=0;i<RecStack.size();++i) RecStack[i]=false;
    52     
    53     for(int i=0;i<G.size();++i){
    54         if(!vis[i]){
    55             vis[i] = true; RecStack[i] = true;
    56             if(isCyclic(edgelist,G,vis,RecStack,i)){
    57                 cout<<i<<" starts a cycle"<<endl; 
    58             }
    59             RecStack[i] = false;
    60         }
    61     }
    62     
    63     return 0;
    64 }
  • 相关阅读:
    SilverLight使用WCF RIA SERVICE实现对数据库的操作 (添加,删除,更新)
    c# 创建、读取、添加、修改xml文件
    Winform 下载文件进度条设计
    WOrd ,excel实现打印功能
    码云与Git的使用
    while循环和字符串格式化
    python环境搭建
    python简介与简单入门
    整型与布尔的转换、字符串的切片和几个常用的方法
    python2与python3的区别
  • 原文地址:https://www.cnblogs.com/fu11211129/p/4903833.html
Copyright © 2020-2023  润新知