E. Reachability from the Capital
题意:一张有向图,现在要求从S出发能到所有点,问至少加几条边
思路:强联通缩点后,判断入度为0的块有几个,S除外
#include<bits/stdc++.h>
#define PI acos(-1.0)
#define pb push_back
#define F first
#define S second
using namespace std;
typedef long long ll;
const int N=5005;
const int MOD=1e9+7;
vector <int> edge[N];
int n,m,SSS,cur,cnt,top,mp[N],DFN[N],LOW[N],s[N];
struct node{int a;int b;}p[N];
int in[N];
void tarjan(int u){
DFN[u]=LOW[u]=++cur;
s[++top]=u;
for(int i=0;i<(int)edge[u].size();i++){
int v=edge[u][i];
if(!DFN[v]){
tarjan(v);
LOW[u]=min(LOW[u],LOW[v]);
}
else if(DFN[v] && !mp[v]) LOW[u]=min(LOW[u],DFN[v]);
}
if(DFN[u]==LOW[u]){
int v=-1;
cnt++;
while(u!=v){
v=s[top--];
mp[v]=cnt;
// cout << v<<" ";
}
// puts("************");
}
}
int main(void){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin >>n>>m>>SSS;
for(int i=1;i<=m;i++){
int u,v;
cin >>u>>v;
p[i].a=u,p[i].b=v;
edge[v].pb(u);
}
ll ans=0;
for(int i=1;i<=n;i++)
if(!DFN[i]) tarjan(i);
// cout <<"cnt="<<cnt<<endl;
for(int i=1;i<=m;i++){
int a=p[i].a,b=p[i].b;
if(mp[a]==mp[b]) continue;
in[mp[b]]++;
}
for(int i=1;i<=cnt;i++){
if(i==mp[SSS]) continue;
// cout <<i << endl;
if(in[i]==0) ans++;
}
cout << ans << "\n";
return 0;
}