题意
N个学校,每个学校维护一个列表,当该学校接收到信息后会转发到列表中的学校。先输入N,然后N行,每行以0结束,表示每个学校维护的列表,问:
(1)至少将信息发送到几个学校,才可以通知到所有学校。
(2)至少加几条边才可以使得,将信息发到任意一个学校都可以通知到所有学校。
思路
缩点:其实也就是给每个强连通分量标号,把相同标号的看作一个点。
把强连通分量缩成一个点,得到一个DAG图。设接下来有cnt1个结点入度为0,cnt2个结点出度为0,cnt1就为第一问的答案,max(a,b)就是第二问的答案。注意特殊情况:当原图已经强连通时,答案是1,0。
//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;
const int MAXN = 1e5+5;
struct Edge
{
int from, to;
Edge (int from, int to): from(from), to(to) {}
};
struct SCC
{
int n, m;
int DFN[MAXN], LOW[MAXN], sccno[MAXN], dfs_clock, scc_cnt;
vector<Edge> edges;
vector<int> G[MAXN];
stack<int> S;
void init(int n)
{
this->n = n, m = 0;
edges.clear();
for (int i = 0; i <= n; i++) G[i].clear();
}
void AddEdge (int from, int to)
{
edges.push_back(Edge(from, to));
m = edges.size();
G[from].push_back(m-1);
}
void dfs(int u)
{
DFN[u] = LOW[u] = ++dfs_clock;
S.push(u);
for (int i = 0; i < G[u].size(); i++)
{
Edge e = edges[G[u][i]];
int v = e.to;
if (!DFN[v])
{
dfs(v);
LOW[u] = min(LOW[u], LOW[v]);
}
else if (!sccno[v])
LOW[u] = min(LOW[u], DFN[v]);
}
if (LOW[u] == DFN[u])
{
scc_cnt++;
while (1)
{
int x = S.top(); S.pop();
sccno[x] = scc_cnt;
if (x == u) break;
}
}
}
void find_scc()
{
dfs_clock = scc_cnt = 0;
memset(DFN, 0, sizeof(DFN)), memset(sccno, 0, sizeof(sccno));
for (int i = 0; i < n; i++)
if (!DFN[i]) dfs(i);
}
}gao;
int n, in0[MAXN], out0[MAXN];
int main()
{
scanf("%d", &n);
gao.init(n);
for (int i = 0; i < n; i++)
{
int x;
while (~scanf("%d", &x) && x)
gao.AddEdge(i, x-1);
}
gao.find_scc();
for (int i = 0; i < gao.m; i++)
{
int u = gao.edges[i].from, v = gao.edges[i].to;
if (gao.sccno[u] != gao.sccno[v])
in0[gao.sccno[v]]++, out0[gao.sccno[u]]++;
}
int cnt1 = 0, cnt2 = 0;
for (int i = 1; i <= gao.scc_cnt; i++)
{
if (!in0[i]) cnt1++;
if (!out0[i]) cnt2++;
}
if (gao.scc_cnt == 1) printf("1\n0\n");
else printf("%d\n%d\n", cnt1, max(cnt1, cnt2));
return 0;
}
/*
5
2 4 3 0
4 5 0
0
0
1 0
*/