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

版权声明:叁土 https://blog.csdn.net/qq_42847312/article/details/84865548

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

————
余生还请多多指教!

猜你喜欢

转载自blog.csdn.net/qq_42847312/article/details/84865548
今日推荐