C++ 如何确定整个图是否是一个强连通分量?
我有这段代码,用于查找图是否是强连通组件C++ 如何确定整个图是否是一个强连通分量?,c++,graph,C++,Graph,我有这段代码,用于查找图是否是强连通组件 vector<int> G[2005]; int depth = 0; void dfs(int u) { visited[u] = 1; low[u] = ++depth; for(int i=0;i<G[u].size();++i) { int v = G[u][i]; if(!visited[v]) dfs(v); low[u] = min(low[u],low[v]);
vector<int> G[2005];
int depth = 0;
void dfs(int u)
{
visited[u] = 1;
low[u] = ++depth;
for(int i=0;i<G[u].size();++i)
{
int v = G[u][i];
if(!visited[v])
dfs(v);
low[u] = min(low[u],low[v]);
}
}
vectorg[2005];
int深度=0;
无效dfs(int u)
{
访问[u]=1;
低[u]=++深度;
对于(inti=0;i我将使用
本质上,它是如何计算时间O(| E |)
中的强连接组件的。然后,您可以简单地查看SCC的数量。如果不是1,则整个图不是一个SCC。此外,您可以提供早期退出版本,例如,一旦我发现第二个SCC退出
一些C++作为起始地:(但仍然是伪代码)
vector ComputeSCC(图&g){
int指数=0;
载体sccs;
堆栈s;
//对于每个顶点,抓取SCC
对于(自动v:g.顶点())
如果(v.index=-1)
强连接(g、v、索引、s、SCC);
返回SCC;
}
无效强连接(图形和g、顶点和v、整数和i、堆栈和s、向量和sccs){
v、 指数=i;
v、 lowlink=i;
i++;
s、 推回(v);
//对于每个继任者
对于(自动e:v.继承人()){
如果(如target().index==-1){
strong连接(例如,target(),i,sccs);
v、 lowlink=min(v.lowlink,e.target().lowlink);
}
其他的
v、 lowlink=min(v.lowlink,e.target().index);
}
//如果v是根节点,则弹出堆栈并生成SCC
if(v.lowlink==v.index){
sccs.推回(SCC());
顶点w;
做{
w=S.pop();
sccs.back().向后推(w);
}而(w!=v);
}
}
你的数据结构是什么?基本上,当你标记访问的节点时,图形遍历应该是有效的。你在每次递归时增加深度。因此,当我认为每个G[u][i]的深度在相同的for循环中应该相同时,它们的深度可能会不同。是的,但我添加了一行low[u]=min(low[u],low[v])
因此,如果是一个连接的组件,则最低值应为1。因为我已从顶点1开始搜索。我是否应该像tarjans算法那样保留堆栈?因为我不需要解决方案,所以我不应该需要堆栈。如果您只想确定它是否是一个SCC,您可能不需要这样做。一旦我尝试创建新的SCCSCC(在第一个之后)中断递归并停止。我已经按照你说的做了,这是我的代码,但是我看到我在那里给出的输入失败了。你可以在你的语句中查看这个问题if(!visted[v])
你还需要low[u]=min(low[u],low(v))
谢谢你的回答,我仍然得到了错误的答案,肯定有一些棘手的情况。但是谢谢你的帮助。
vector<SCC> ComputeSCC(Graph& g) {
int index = 0;
vector<SCC> sccs;
stack<Vertex> s;
//for each vertex grab the SCC
for(auto v : g.vertices())
if(v.index == -1)
StronglyConnected(g, v, index, s, sccs);
return sccs;
}
void StronglyConnected(Graph& g, Vertex& v, int& i, stack<Vertex>& s, vector<SCC>& sccs) {
v.index = i;
v.lowlink = i;
i++;
s.push_back(v);
//for each successor
for(auto e : v.successors()) {
if(e.target().index == -1) {
StronglyConnected(g, e.target(), i, sccs);
v.lowlink = min(v.lowlink, e.target().lowlink);
}
else
v.lowlink = min(v.lowlink, e.target().index);
}
//If v is a root node, pop the stack and generate an SCC
if(v.lowlink == v.index) {
sccs.push_back(SCC());
Vertex w;
do {
w = S.pop();
sccs.back().push_back(w);
} while(w != v);
}
}