tarjan 算法模板
做了一些树形DP实在不想做了看到von在玩tarjan算法,好像放假之前看过关于rmq 以及tarjan算法的说明只是没具体弄明白。今天看了一下von分享的资料不错。找了一个模板题就当tarjan算法的模板吧
http://acm.hdu.edu.cn/showproblem.php?pid=1269
判断是否为强连通图 bcnt == 1只有一个强连通分量且为自己 bcnt >1 存在多个强连通分量
View Code
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#define maxn 10007
using namespace std;
vector<int>g[maxn];
int DFN[maxn],LOW[maxn],Belong[maxn],stack[maxn];
bool instack[maxn];
int n,m;
int bcnt,top,index;
void tarjan(int i)
{
int j;
DFN[i] = LOW[i] = ++index;
stack[++top] = i;
instack[i] = true;
int size = g[i].size();
for (int k = 0; k < size; ++k)
{
j = g[i][k];
if(!DFN[j])
{
tarjan(j);
if(LOW[j] < LOW[i])
LOW[i] = LOW[j];
}
else if(instack[j] && DFN[j] < LOW[i])
{
LOW[i] = DFN[j];
}
}
if(DFN[i] == LOW[i])
{
bcnt ++;
do
{
j = stack[top--];
instack[j] = false;
Belong[j] = bcnt;
}while(j != i);
}
}
void solve()
{
int i;
bcnt = top = index = 0;
for (i = 1; i <= n; ++i)
{
if(!DFN[i])
tarjan(i);
}
if(bcnt == 1)
printf("Yes\n");
else
printf("No\n");
}
int main()
{
int i,x,y;
while(cin>>n>>m)
{
if(!n && !m) break;
for (i = 0; i <= n; ++i)
{
DFN[i] = LOW[i] = Belong[i] = 0;
instack[i] = false;
g[i].clear();
}
for (i = 0; i < m; ++i)
{
cin>>x>>y;
g[x].push_back(y);
}
solve();
/*for (i = 1; i <= n; ++i)
{
printf("%d ",Belong[i]);
}
printf("\n");*/
}
return 0;
}