这道题,建图灰常的好建,就是把命题当成点,把证明关系当成有向边,求得就是最少加多少条边,使得整个图强连通。求一个强连通分量,然后答案就是出度为零的点和入度为零的点的最大值,因为只有出度或入度为零的点都连上边才能保证整个图都是强联通的。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int N = 22222;
int pre[N], lowlink[N], sccno[N], dfs_clock, scc_cnt, n, m;
int in0[N], out0[N];
vector<int> G[N];
stack<int> S;
void dfs(int u){
pre[u] = lowlink[u] = ++dfs_clock;
S.push(u);
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
if (!pre[v]){
dfs(v);
lowlink[u] = min(lowlink[u], lowlink[v]);
}
else if (!sccno[v]){
lowlink[u] = min(lowlink[u], pre[v]);
}
}
if (lowlink[u] == pre[u]){
scc_cnt += 1;
for (; ;){
int x = S.top(); S.pop();
sccno[x] = scc_cnt;
if (x == u) break;
}
}
}
void tarjan(int n){
dfs_clock = scc_cnt = 0;
memset(sccno, 0, sizeof(sccno));
memset(pre, 0, sizeof(pre));
for (int i = 0; i < n; i++)
if (!pre[i]) dfs(i);
}
int main(){
int cs; scanf("%d", &cs);
while(cs--){
scanf("%d%d", &n, &m);
for (int i = 0; i <= n; i++)
G[i].clear();
int x, y;
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
x -= 1; y -= 1;
G[x].push_back(y);
}
tarjan(n);
for (int i = 1; i <= scc_cnt; i++)
in0[i] = out0[i] = 1;
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]) in0[sccno[v]] = out0[sccno[u]] = 0;
}
int a = 0, b = 0;
for (int i = 1; i <= scc_cnt; i++){
if (in0[i]) a += 1;
if (out0[i]) b += 1;
}
int ans = max(a, b);
if (scc_cnt == 1) ans = 0;
printf("%d\n", ans);
}
return 0;
}