HDU 迷宫城堡 强连通图 kosaraju and tarjan
kosaraju解法:
#include<iostream>
#include<stack>
#include<vector>
#include<algorithm>
#include<string.h>
#include<cstdio>
int n, m;
bool b[10002];
using namespace std;
vector<int> go[10002],goback[10002];
bool kosaraju(int k, vector<int> *go1)
{
stack<int> Q; int cont = 0;
Q.push(1); b[1] = true;
while (!Q.empty())
{
cont++;
int a = Q.top(); Q.pop();
int length = go1[a].size();
for (int i = 0; i < length; i++)
{
if (b[go1[a][i]] == true) continue;
Q.push(go1[a][i]); b[go1[a][i]] = true;
}
}
if (cont == n) return true;
return false;
}
int main()
{
while (cin >> n >> m && (n + m))
{
for (int i = 0; i < m; i++)
{
int a, b;
scanf_s("%d%d", &a, &b);
go[a].push_back(b);
}
memset(b, false, sizeof(b));
if (!kosaraju(1,go))
{
cout << "No" << endl;
for (int i = 1; i <= n; i++)
{
go[i].clear();
goback[i].clear();
}
continue;
}
memset(b, false, sizeof(b));
for (int i = 1; i <= n; i++)
{
int tt = go[i].size();
for (int j = 0; j < tt; j++)
{
goback[go[i][j]].push_back(i);
}
}
if (!kosaraju(1, goback))
{
cout << "No" << endl;
for (int i = 1; i <= n; i++)
{
go[i].clear();
goback[i].clear();
}
continue;
}
cout << "Yes" << endl;
for (int i = 1; i <= n; i++)
{
go[i].clear();
goback[i].clear();
}
}
return 0;
}