牛客-15705 可达性
可达性
\(tarjan\) 缩点
如果是 \(DAG\) 图,则答案就是入度为 \(0\) 的强连通分量中字典序最小的点组成的点集
因此直接缩点,然后维护每个强连通分量的最小字典序的点
#include <iostream>
#include <cstdio>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 1e5 + 10;
vector<int>gra[maxn];
int low[maxn], dfn[maxn], tp = 0;
int vis[maxn], du[maxn];
int scc[maxn], cnt_scc = 0;
int minn[maxn];
stack<int>st;
void tarjan(int now)
{
st.push(now);
vis[now] = 1;
dfn[now] = low[now] = ++tp;
for(int nex : gra[now])
{
if(dfn[nex] == 0)
{
tarjan(nex);
low[now] = min(low[nex], low[now]);
}
else if(vis[nex])
low[now] = min(low[nex], low[now]);
}
if(low[now] == dfn[now])
{
cnt_scc++;
minn[cnt_scc] = maxn + 10;
while(st.top() != now)
{
int x = st.top();
st.pop();
vis[x] = 0;
scc[x] = cnt_scc;
minn[cnt_scc] = min(minn[cnt_scc], x);
}
st.pop();
vis[now] = 0;
scc[now] = cnt_scc;
minn[cnt_scc] = min(minn[cnt_scc], now);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
for(int i=0; i<m; i++)
{
int a, b;
cin >> a >> b;
gra[a].push_back(b);
}
for(int i=1; i<=n; i++)
if(dfn[i] == 0) tarjan(i);
for(int i=1; i<=n; i++)
for(int nex : gra[i])
if(scc[i] != scc[nex])
du[scc[nex]]++;
int cur = 0, ans = 0;
for(int i=1; i<=cnt_scc; i++) if(du[i] == 0) ans++;
cout << ans << endl;
for(int i=1; i<=cnt_scc; i++)
{
if(du[i] == 0)
{
if(cur++) cout << " ";
cout << minn[i];
}
}
cout << endl;
}