# Wannafly挑战赛14C 可达性（Tarjan 缩点）

## 可达性

• 时间限制：C/C++ 1秒，其他语言2秒
• 空间限制：C/C++ 262144K，其他语言524288K
• 64bit IO Format: %lld

### 输入

7 10
4 5
5 1
2 5
6 5
7 2
4 2
1 2
5 3
3 5
3 6

### 输出

2
4 7

### 链接

https://www.nowcoder.com/acm/contest/81/C

### 题解

Tarjan模板题，求强联通分量后缩点，得到DAG图，选择每一个入度为0的强连通分量中序号最小的点

### 代码

127179602388
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
using namespace std;
const int maxn = 100010;
vector <int> E[maxn];
vector <int> G[maxn];
vector <int> ans;
int n, m;
int tot, scc_cnt;

int dfn[maxn], low[maxn], sccno[maxn], inde[maxn];
bool vis[maxn];
stack <int> s;

void tarjan(int x) // 求强连通分量
{
dfn[x] = low[x] = ++tot;
s.push(x);
vis[x] = true;
for (int i = 0; i < G[x].size(); ++i)
{
int v = G[x][i];
if (!dfn[v])
{
tarjan(v);
low[x] = min(low[x], low[v]);
}
else if (vis[v])
low[x] = min(low[x], dfn[v]);
}
if (dfn[x] == low[x])
{
++scc_cnt;
while (1)
{
int u = s.top();
s.pop();
vis[u] = 0;
sccno[u] = scc_cnt;
E[scc_cnt].push_back(u); // 得到每一个强连通分量
if (u == x)
break;
}
}
}

void find_scc()
{
memset(vis, 0, sizeof(vis));
memset(dfn, 0, sizeof(vis));
memset(low, 0, sizeof(low));
memset(sccno, 0, sizeof(sccno));
tot = scc_cnt = 0;
for (int i = 0; i < n; ++i)
if (!dfn[i])
tarjan(i);
}

int main()
{
int u, v;
while (scanf("%d%d", &n, &m) != EOF)
{
for (int i = 0; i <= n; ++i)
{
G[i].clear();
E[i].clear();
}
ans.clear();
for (int i = 0; i < m; ++i)
{
scanf("%d%d", &u, &v);
u--;
v--;
G[u].push_back(v);
}
find_scc();
memset(inde, 0, sizeof(inde));
for (int u = 0; u < n; ++u) // 缩点建图
{
for (int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i];
if (sccno[u] != sccno[v])
inde[sccno[v]]++;
}
}
for (int i = 1; i <= scc_cnt; ++i)
{
if (inde[i] == 0)
ans.push_back(*min_element(E[i].begin(), E[i].end()));
}
printf("%d\n", ans.size());
printf("%d", ans[0] + 1);
for (int i = 1; i < ans.size(); ++i)
printf(" %d", ans[i] + 1);
printf("\n");
}
return 0;
}

The end.
2018-04-26 星期四