數據結構實驗之圖論十:判斷給定圖是否存在合法拓撲序列
Time Limit: 1000 ms Memory Limit: 65536 KiB
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
拓撲排序算法:
void TopSort ( )
{
queue <int> Q;
int counter = 0;
Vertex V, W;
for( each vertex V ) //圖中每個頂點
{
if( Indegree[V] == 0 ) //入度爲零
Q.push( V );
}
while( !Q.empty() )
{
V = Q.front();
Q.pop();
TopNum[counter++] = V; //記錄V的輸出序號
for( each W adjacent to V )
{
if( --Indegree[W] == 0 )
Q.push( W );
}
}
if( counter != NumVertex )
ERROR ( "Graph has a cycle" );
}
有合法的拓撲排序需要不是無向有環圖;進行廣搜,如果搜到遍歷過的點就是有環圖了;
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
int G[1100][1100];
int visit[1100];
int now, i, j, n, m;;
queue<int> Q;
void BFS( )
{
int flag = 1;
Q.push(1);
visit[1] = 1;
while( !Q.empty() )
{
now = Q.front();
Q.pop();
for( i=1; i<=n; i++ )
{
if( G[now][i] )
{
if( !visit[i] )
{
visit[i] = 1;
Q.push(i);
}
else
{
flag = 0;
break;
}
}
}
if(!flag) break;
}
if(flag) cout << "YES" << endl;
else cout << "NO" << endl;
}
int main()
{
while( cin >> n >> m )
{
memset( G, 0, sizeof(G) );
memset( visit, 0, sizeof(visit) );
while( m-- )
{
int a, b;
cin >> a >> b;
G[a][b] = 1;
}
BFS();
}
return 0;
}