Input
On the first line one positive number: the number of testcases, at most 100. After that per testcase:
- One line containing two integers n (1 ≤ n ≤ 20000) and m (0 ≤ m ≤ 50000): the number of statements and the number of implications that have already been proved.
- m lines with two integers s1 and s2 (1 ≤ s1, s2 ≤ n and s1 ≠ s2) each, indicating that it has been proved that statement s1 implies statement s2.
Output
Per testcase:
- One line with the minimum number of additional implications that need to be proved in order to prove that all statements are equivalent.
Sample Input
2
4 0
3 2
1 2
1 3
Sample Output
4
2
求再连几条边让该有向图是一个强连通,
因为强连通没有出入度=0的点,
所以 ans = max(sum(in[i]==0), sum(out[i]==0))
代码
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N=2e4+5;
int head[N<<2],tot;
struct Edge{
int from,to,next;
Edge(){}
Edge(int from,int to):from(from),to(to){next=head[from];}
}E[N<<2];
inline void addedge(int u,int v){
E[tot]=Edge(u,v),head[u]=tot++;
}
int low[N],dfn[N],sta[N],scc[N],insta[N];
int id,top,cnt;
void tarjan(int u,int v=0){
low[sta[++top]=u]=dfn[u]=++id;insta[u]=1;
for(int i=head[u];~i;i=E[i].next){
v=E[i].to;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(insta[v])low[u]=min(low[u],dfn[v]);
}
if(low[u]^dfn[u])return;
++cnt;
do{
v=sta[top--];
scc[v]=cnt;
insta[v]=0;
}while(u^v);
}
int n,m,u,v,t,i;
int in[N],out[N];
void init(){
for(int i=1;i<=n;++i)dfn[i]=in[i]=out[i]=insta[i]=0;
memset(head,-1,sizeof(head));
cnt=top=tot=id=0;
}
int main(){
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
init();
while(m--)scanf("%d%d",&u,&v),addedge(u,v);
for(i=1;i<=n;++i)if(!dfn[i])tarjan(i);
for(i=0;i<tot;++i){
u=scc[E[i].from],v=scc[E[i].to];
if(u^v)++in[v],++out[u];
}
for(i=1,u=0,v=0;i<=cnt;++i)u+=!in[i],v+=!out[i];
printf("%d\n",cnt>1?max(u,v):0);
}
return 0;
}