很裸的强连通分量。
Tarjan 缩点后,统计入度为 (0) 的点的个数,直接输出即可。
#include <bits/stdc++.h>
using namespace std;
inline int gi()
{
int f = 1, x = 0; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return f * x;
}
const int INF = 0x3f3f3f3f, N = 1003, M = N * N;
int n, m;
int head[N], headc[N], ver[M], nxt[M], tot;
int dfn[N], low[N], tim, stk[N], topp, scc_cnt, id[N];
bool in_stk[N];
int in[N];
inline void add(int h[], int u, int v)
{
ver[++tot] = v, nxt[tot] = h[u], h[u] = tot;
}
void Tarjan(int u)
{
dfn[u] = low[u] = ++tim, stk[++topp] = u, in_stk[u] = true;
for (int i = head[u]; i; i = nxt[i])
{
int v = ver[i];
if (!dfn[v])
{
Tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (in_stk[v]) low[u] = min(low[u], dfn[v]);
}
if (dfn[u] == low[u])
{
int y = -1;
++scc_cnt;
do
{
y = stk[topp--];
in_stk[y] = false;
id[y] = scc_cnt;
} while (y != u);
}
}
int main()
{
n = gi();
for (int i = 1; i <= n; i+=1)
for (int j = 1; j <= n; j+=1)
{
int x = gi();
if (x) add(head, i, j);
}
for (int i = 1; i <= n; i+=1) if (!dfn[i]) Tarjan(i);
for (int u = 1; u <= n; u+=1)
for (int i = head[u]; i; i = nxt[i])
{
int v = ver[i];
if (id[u] != id[v])
add(headc, id[u], id[v]), ++in[id[v]];
}
int ans = 0;
for (int i = 1; i <= scc_cnt; i+=1)
if (!in[i])
++ans;
cout << ans << endl;
return 0;
}