dataStructure@ Check if a directed graph has cycles

时间:2024-01-01 11:10:15
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<limits>
#include<vector>
using namespace std;
const int maxn = ;
struct edge{
int to, cost;
edge(int t){
this->to = t; this->cost = ;
}
};
void addEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
edgelist.push_back(edge(to));
G[from].push_back(edgelist.size()-);
}
void addDoubleEdge(vector<edge> &edgelist, vector<vector<int> > &G, int from, int to){
addEdge(edgelist,G,from,to);
addEdge(edgelist,G,to,from);
}
bool isCyclic(vector<edge> edgelist, vector<vector<int> > G,vector<bool> vis, vector<bool> RecStack, int v){
for(int i=;i<G[v].size();++i){
edge e = edgelist[G[v][i]];
if(RecStack[e.to]) return true;
if(!vis[e.to]){
vis[e.to] = true; RecStack[e.to] = true;
if(isCyclic(edgelist,G,vis,RecStack,e.to)) return true;
RecStack[e.to] = false;
}
}
return false;
}
void buildMap(vector<edge> &edgelist, vector<vector<int> > &G){
addEdge(edgelist,G,,);
addEdge(edgelist,G,,);
addEdge(edgelist,G,,);
addEdge(edgelist,G,,);
addEdge(edgelist,G,,);
addEdge(edgelist,G,,);
}
int main(){
vector<edge> edgelist;
vector<vector<int> > G(maxn);
vector<bool> vis(maxn);
vector<bool> RecStack(maxn); buildMap(edgelist,G); for(int i=;i<vis.size();++i) vis[i]=false;
for(int i=;i<RecStack.size();++i) RecStack[i]=false; for(int i=;i<G.size();++i){
if(!vis[i]){
vis[i] = true; RecStack[i] = true;
if(isCyclic(edgelist,G,vis,RecStack,i)){
cout<<i<<" starts a cycle"<<endl;
}
RecStack[i] = false;
}
} return ;
}