题目大意
一个有向图,问最少添加几个点能使整个图成为一个强连通图
思路
tarjan求强连通分量,缩点,如果只有一个强连通分量,说明整个图本身就是一个强连通图,如果有多个强连通分量,求每一个强连通分量的入度和出度,入度为0的点和出度为0的点的最大值就是结果,因为如果一个图强连通,需要每一个点都至少有一个出度一个入度,添加一个边会影响一对出度和入度,因此取最大值
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#define mem(a) memset(a, 0, sizeof (a))
using namespace std;
const int maxn = 50010;
int n, m, k, top, num, cnt, low[maxn], dfn[maxn], node[maxn], nex[maxn], head[maxn], v[maxn], st[maxn], Count[maxn], c[maxn];
int node1[maxn], head1[maxn], nex1[maxn], vis[maxn];
void pre_work(){
mem(node1), mem(head1), mem(nex1), mem(dfn), mem(node), mem(low), mem(head), mem(v), mem(st), mem(c), mem(Count);
mem(vis);
}
void add(int x, int y){
++k;
node[k] = y;
nex[k] = head[x];
head[x] = k;
}
void add1(int x, int y){
++k;
node1[k] = y;
nex1[k] = head1[x];
head1[x] = k;
}
void init(){
cnt = 0;
num = 0;
k = 0;
top = 0;
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++){
int a, b;
scanf("%d %d", &a, &b);
add(a, b);
}
}
void tarjan(int x){
v[x] = 1;
st[++top] = x;
dfn[x] = low[x] = ++num;
for (int i = head[x]; i; i = nex[i]){
int y = node[i];
if(!dfn[y]){
tarjan(y);
low[x] = min(low[x], low[y]);
}
else if(v[y]){
low[x] = min(low[x], dfn[y]);
}
}
if(dfn[x] == low[x]){
++cnt;
while (1){
int t = st[top--];
v[t] = 0;
c[t] = cnt;
Count[cnt]++;
if(t == x)break;
}
}
}
void solve(){
for (int i = 1; i <= n; i++){
if(!dfn[i])tarjan(i);
}
k = 0;
for (int i = 1; i <= n; i++){
for (int j = head[i]; j; j = nex[j]){
if(c[i] != c[node[j]]){
add1(c[i], c[node[j]]);
vis[c[node[j]]] = 1;
}
}
}
int ans = 0, res = 0;
if(cnt == 1){
puts("0");
return;
}
for (int i = 1; i <= cnt; i++){
if(head1[i] == 0){
++res;//out
}
if(vis[i] == 0)++ans;
}
printf("%d\n", max(ans, res));
}
int main()
{
int T;
scanf("%d", &T);
while (T--){
pre_work();
init();
solve();
}
return 0;
}