Time Limit: 2000MS | Memory Limit: 65536K | |
Description
Input
Output
Sample Input
1 3 3 1 2 2 3 3 1
Sample Output
Yes
Source
#include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <stack> #include <queue> #include <algorithm> using namespace std; const int Max = 1100; const int INF = 0x3f3f3f3f; typedef struct node { int v; int next; }Line ; Line Li[Max*6]; int Head[Max],top; int Map[Max][Max]; int Du[Max],pre[Max]; int vis1[Max],dfn[Max],low[Max]; bool vis2[Max]; int dep; int Point[Max*5][2],Num; int topo[Max],num; int a[Max],ToNum; stack < int >S; void AddEdge(int u,int v) { Li[top].v = v; Li[top].next = Head[u]; Head[u] = top++; } int Find(int x) { return pre[x]==-1?x:pre[x] = Find(pre[x]); } void Tarjan(int u) //强连通缩点 { dfn[u] = low[u] = dep++; vis1[u] = 1; S.push(u); for(int i=Head[u];i!=-1;i=Li[i].next) { if(vis1[Li[i].v]==1) { low[u]=min(low[u],dfn[Li[i].v]); } if(vis1[Li[i].v]==0) { Tarjan(Li[i].v); low[u]=min(low[u],low[Li[i].v]); } if(vis2[Li[i].v]) { Point[Num][0]=u; Point[Num++][1]=Li[i].v; } } if(low[u]==dfn[u]) //如果low[u]==dfn[u],则说明是强连通的根节点。 { vis2[u]=true; topo[num++] = u; while(1) { if(S.empty()) { break; } int v = S.top(); S.pop(); vis1[v]=2; if(v==u) { break; } pre[v]=u; } } } void Toposort()//BFS拓扑排序 { queue<int>Q; for(int i=0;i<num;i++) { if(Du[topo[i]]==0) { Q.push(topo[i]); } } while(!Q.empty()) { int u=Q.front(); a[ToNum++]=u; Q.pop(); for(int i=0;i<num;i++) { if(Map[u][topo[i]]) { Du[topo[i]]--; if(Du[topo[i]]==0) { Q.push(topo[i]); } } } } } int main() { int T; int n,m; scanf("%d",&T); while(T--) { scanf("%d %d",&n,&m); top = 0; memset(Head,-1,sizeof(Head)); int u,v; for(int i=0;i<m;i++) { scanf("%d %d",&u,&v); AddEdge(u,v); } memset(vis1,0,sizeof(vis1)); memset(Map,0,sizeof(Map)); memset(vis2,false,sizeof(vis2)); memset(Du,0,sizeof(Du)); memset(pre,-1,sizeof(pre)); dep = 0; Num =0 ;num = 0; while(!S.empty()) { S.pop(); } for(int i=1;i<=n;i++) { if(vis1[i]==0) { Tarjan(i); } } for(int i=0;i<Num;i++) { int x = Find(Point[i][0]); int y = Find(Point[i][1]); Map[x][y]=1; Du[y]++; } ToNum = 0; Toposort(); bool flag=false; for(int i=0;i<ToNum-1;i++) { if(!Map[a[i]][a[i+1]])//判断相邻的是不是存在边 { flag=true; break; } } if(flag) { printf("No\n"); } else { printf("Yes\n"); } } return 0; }