我最近学习了线性时间算法来计算图表中的关节点。我的实现在 Online Judge Test Data 上正确运行,因此代码没有问题。但是,我似乎很难在 DFS 运行中如何出现多个相同的关节点。让我解释
我有一个列表,如果遇到关节点,则存储它们。现在,当我最后打印列表时,我得到了正确的关节点,但是作为关节点的几个顶点不止一次出现在列表中。根据我的说法,这不应该发生,因为我们只遇到每个顶点一次。那么为什么我会在列表中重复输入?为了解决这个问题,我在原始代码中使用了一个 HashSet 来存储它们,最后只打印了给出正确答案的内容。这是我的问题代码。该算法主要基于维基百科上的伪代码:https ://en.wikipedia.org/wiki/Biconnected_component
这是我在 C++ 中的实现代码:
/*input
7 6
0 1
1 2
3 4
2 4
2 6
5 2
*/
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define pb emplace_back
#define sz 3005 //In the current scenario, I need only a maximum on 3000 vertices
typedef long long int ll;
//Created by Shreyans Sheth [bholagabbar]
bool visited [sz]; //whether the node has been discoverd in the DFS run or not
int low [sz]; //time of the earliest discovered vertex reachable from the vertex
int disc [sz]; //time at which vertex was explored
int parent [sz]; //stores the parents of each vertex
vector<int> a[sz]; //Adjacency List for graph
int rtime; //Time
vector<int> ap; //Stored the articulation points
void DFS(int s)
{
visited[s]=1;
low[s]=disc[s]=++rtime;
int nchild=0;
for(auto i:a[s])
{
if(!visited[i])
{
nchild++;//INcrement children of the current vertex
parent[i]=s;
DFS(i);
low[s]=min(low[s],low[i]);
/* s is an articulation point iff
1. It the the root and has more than 1 child.
2. It is not the root and no vertex in the subtree rooted at one of its
children has a back-link to its ancestor.
A child has a back-link to an ancestor of its parent when its low
value is less than the discovery time of its parent.*/
if((parent[s]==-1 && nchild>1)||(parent[s]!=-1 && low[i]>=disc[s]))
ap.pb(s);//Adding the articulation points. How are they repeated?
}
else if(visited[i] && i!=parent[s])
low[s]=min(low[s],disc[i]);
}
}
void ArticulationPoints(int n)//Driver Funtion
{
ap.clear();
rtime=0;//The time for each cycle of DFS
for(int i=0;i<n;i++)
{
parent[i]=-1;//Initializing parents as -1. True for roots
visited[i]=0;//All points not visited
low[i]=disc[i]=INT_MAX;
}
for(int i=0;i<n;i++)
if(!visited[i])//Vertex not discoverdd
DFS(i);
}
int main()
{
int n,m;//number of vertices, edges
cin>>n>>m;
for(int i=0;i<m;i++)//Building Graph
{
int x,y;
cin>>x>>y;
a[x].pb(y);
a[y].pb(x);
}
ArticulationPoints(n);//Calculating Articulation points
cout<<"Articulation Points are:\n";
for(int i:ap)
cout<<i<<endl;
return 0;
}
带有输入和输出的代码:http: //ideone.com/u5dYOy(看看 2 是怎么来的三次?)
为什么会这样?我在算法中遗漏了什么吗?我相信我对算法的运行有一个很好的了解。任何帮助表示赞赏。谢谢