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

来源:互联网 发布:淘宝大连博哲贸易 编辑:程序博客网 时间:2024/05/22 16:00

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

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic

Problem Description

 给定一个有向图,判断该有向图是否存在一个合法的拓扑序列。

Input

 输入包含多组,每组格式如下。

第一行包含两个整数n,m,分别代表该有向图的顶点数和边数。(n<=10)

后面m行每行两个整数a b,表示从a到b有一条有向边。

 

Output

 若给定有向图存在合法拓扑序列,则输出YES;否则输出NO。

 

Example Input

1 02 21 22 1

Example Output

YESNO

Hint

Author

 赵利强 

#include <iostream>
#include <cstring>
using namespace std;
int map[15][15];
int in[15];
int vis[15];
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        memset(map,0,sizeof(map));
        memset(in,0,sizeof(in));
        memset(vis,0,sizeof(vis));


        int i,j;
        int a,b;
        int cnt=n;
        for(i=1; i<=m; i++)
        {
            cin>>a>>b;
            map[a][b]=1;
            in[b]++;
        }
        for(i=1; i<=n; i++)
        {
            for(j=1; j<=n; j++)
            {
                if(vis[j]==0&&in[j]==0)
                {
                    cnt--;
                    vis[j]=1;
                    for(int k=1; k<=n; k++)
                    {
                        if(map[j][k]==1)
                        {
                            in[k]--;
                        }
                    }
                }
            }
        }
        if(cnt)
            cout<<"NO"<<endl;
        else
            cout<<"YES"<<endl;
    }


    return 0;
}

阅读全文
0 0
原创粉丝点击