SDUT OJ 数据结构实验之图论十:判断给定图是否存在合法拓扑序列

数据结构实验之图论十:判断给定图是否存在合法拓扑序列

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

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;
}

猜你喜欢

转载自blog.csdn.net/winner647520/article/details/81346849