BOTTOM - The Bottom of a Graph
考虑缩点。
发现对于每一个强连通分量的每个点,都满足能到其所在强连通分量的每个点然后走回来。
但是这个点能到其他强连通分量的点走回来吗?并不是的。由于缩点完是有向无环图,所以只有缩点后出度为 的强连通分量内的所有点满足题意。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 50005;
vector<int> G[N];
int dfn[N], low[N], stk[N], top, idx;
bool in_stk[N];
int in[N], scc_cnt, id[N];
vector<int> ve[N];
int n, m;
int u[N], v[N];
void tarjan(int u)
{
::dfn[u] = ::low[u] = ++::idx;
::in_stk[u] = 1;
::stk[++::top] = u;
for (auto& j : ::G[u])
{
if (!::dfn[j])
{
tarjan(j);
::low[u] = ::min(::low[u], ::low[j]);
}
else if (::in_stk[j]) ::low[u] = ::min(::low[u], ::dfn[j]);
}
if (::dfn[u] == ::low[u])
{
::scc_cnt++;
int y = 0;
do
{
y = ::stk[::top--];
::in_stk[y] = 0;
::id[y] = ::scc_cnt;
::ve[::scc_cnt].emplace_back(y);
} while (y != u);
}
};
int main()
{
while (scanf("%d", &n))
{
if (n == 0) break;
::idx = 0;
::top = ::scc_cnt = 0;
scanf("%d", &m);
for (int i = 1; i <= n; i++) ::G[i].clear(), ::in[i] = 0, ::in_stk[i] = 0, ::ve[i].clear(), ::dfn[i] = ::low[i] = 0;
for (int i = 1; i <= m; i++)
{
int u, v;
scanf("%d%d", &u, &v);
G[u].emplace_back(v);
::u[i] = u, ::v[i] = v;
}
for (int i = 1; i <= ::n; i++)
{
if (!::dfn[i]) ::tarjan(i);
}
for (int i = 1; i <= ::m; i++)
{
int u = ::u[i], v = ::v[i];
if (::id[u] ^ ::id[v])
{
::in[::id[u]]++;
}
}
vector<int> ans;
for (int i = 1; i <= ::scc_cnt; i++)
{
if (::in[i] == 0)
{
for (auto& j : ::ve[i])
{
ans.emplace_back(j);
}
}
}
sort(ans.begin(), ans.end());
for (auto& i : ans)
{
printf("%d ", i);
}
printf("\n");
}
return 0;
}

浙公网安备 33010602011771号