資料結構實驗之圖論十:判斷給定圖是否存在合法拓撲序列__BFS
阿新 • • 發佈:2018-12-09
Problem Description
給定一個有向圖,判斷該有向圖是否存在一個合法的拓撲序列。
Input
輸入包含多組,每組格式如下。
第一行包含兩個整數n,m,分別代表該有向圖的頂點數和邊數。(n<=10)
後面m行每行兩個整數a b,表示從a到b有一條有向邊。
Output
若給定有向圖存在合法拓撲序列,則輸出YES;否則輸出NO。
Sample Input
1 0
2 2
1 2
2 1
Sample Output
YES
NO
AC程式碼:
#include<bits/stdc++.h> using namespace std; int mp[1001][1001],vis[1001],que[1001]; int n,m; void BFS() { int head=0,tail=0,flag=1; vis[1]=1; que[tail]=1; tail++; while(head<tail) { int x=que[head]; for(int i=1; i<=n; i++) { if(mp[x][i]==1) { if(vis[i]==1) { flag=0; break; } else { vis[i]=1; que[tail]=i; tail++; } } } head++; } if(flag==1) cout<<"YES\n"; else cout<<"NO\n"; } int main() { int u,v; while(cin>>n>>m) { memset(mp,0,sizeof(mp)); memset(vis,0,sizeof(vis)); while(m--) { cin>>u>>v; mp[u][v]=1; } BFS(); } return 0; }
————
餘生還請多多指教!