#include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; #define N 30000 int t,n,m,scc,tot,top,clock,x[N],y[N],dfn[N],low[N],f[N][2],stack[N],head[N],belong[N]; bool instack[N]; struct edge{int v,nxt;}e[N]; void add(int x,int y){e[++tot].v=y; e[tot].nxt=head[x]; head[x]=tot;} void init(){ tot=clock=top=scc=0; memset(head,0,sizeof head); memset(e,0,sizeof e); memset(stack,0,sizeof stack); memset(instack,0,sizeof instack); memset(dfn,0,sizeof dfn); memset(low,0,sizeof low); memset(belong,0,sizeof belong); memset(f,0,sizeof f); } void tarjan(int u){ dfn[u]=low[u]=++clock; stack[top++]=u; instack[u]=1; for (int i=head[u];i;i=e[i].nxt){ int v=e[i].v; if (!dfn[v]){tarjan(v); low[u]=min(low[u],low[v]);} else if (instack[v]) low[u]=min(low[u],dfn[v]); } if (dfn[u]==low[u]){ scc++; int v; do{v=stack[--top]; instack[v]=0; belong[v]=scc;}while (v!=u); } } int main(){ scanf("%d",&t); while (t--){ scanf("%d%d",&n,&m); init(); for (int i=1;i<=m;i++){scanf("%d%d",&x[i],&y[i]); add(x[i],y[i]);} for (int i=1;i<=n;i++) if (!dfn[i]) tarjan(i); for (int i=1;i<=m;i++) if (belong[x[i]]!=belong[y[i]]){f[belong[x[i]]][0]++; f[belong[y[i]]][1]++;} int tmp=0; for (int i=1;i<=scc;i++){if (f[i][0]==0) tmp++; if (f[i][1]==0) tmp++;} if (tmp<=2) puts("Yes"); else puts("No"); } return 0; }
|