题目链接:Islands 题目大意:给你一个n个点m条边的有向图,问最少还需要添加多少条边可以使得所有的城市都能到达另外一个城市 题目思路:强连通分量缩点,然后求一下入
题目链接:Islands
题目大意:给你一个n个点m条边的有向图,问最少还需要添加多少条边可以使得所有的城市都能到达另外一个城市
题目思路:强连通分量缩点,然后求一下入度为0的强连通和出度为0的强连通分量,取最小就好了
#include <map>#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <utility>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 20010;
vector<int>Edge[maxn];
stack<int>S;
int Dfn[maxn],Low[maxn],sccno[maxn],tclock,sccnt;
int InDeg[maxn],OutDeg[maxn];
void tarjan(int u){
Dfn[u] = Low[u] = ++tclock;
S.push(u);
for(int i = 0;i < Edge[u].size();i++){
int v = Edge[u][i];
if(!Dfn[v]){
tarjan(v);
Low[u] = min(Low[u],Low[v]);
}
else if(!sccno[v]){
Low[u] = min(Low[u],Dfn[v]);
}
}
if(Low[u] == Dfn[u]){
sccnt += 1;
int v = -1;
while(v != u){
v = S.top();
S.pop();
sccno[v] = sccnt;
}
}
}
void findscc(int n){
tclock = sccnt = 0;
memset(Dfn,0,sizeof(Dfn));
memset(Low,0,sizeof(Low));
memset(sccno,0,sizeof(sccno));
for(int i = 1;i <= n;i++)
if(!Dfn[i]) tarjan(i);
}
int solve(int n){
if(sccnt == 1) return 0;
memset(InDeg,0,sizeof(InDeg));
memset(OutDeg,0,sizeof(OutDeg));
for(int u = 1;u <= n;u++){
for(int i = 0;i < Edge[u].size();i++){
int v = Edge[u][i];
if(sccno[u] != sccno[v]){
InDeg[sccno[v]]++;
OutDeg[sccno[u]]++;
}
}
}
int c1 = 0,c2 = 0;
for(int i = 1;i <= sccnt;i++){
if(InDeg[i] == 0) c1++;
if(OutDeg[i] == 0) c2++;
}
return max(c1,c2);
}
int main(){
int T;
scanf("%d",&T);
while(T--){
int n,m;
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++) Edge[i].clear();
while(m--){
int u,v;
scanf("%d%d",&u,&v);
Edge[u].push_back(v);
}
findscc(n);
printf("%d\n",solve(n));
}
}