拓扑排序判断

来源:互联网 发布:剑雨江湖法器进阶数据 编辑:程序博客网 时间:2024/06/05 07:27

拓扑排序的实现方法:

                                     (1)从有向图中选择一个没有前驱(即入度为0)的顶点并且输出它.

                                     (2)从网中删去该顶点,并且删去从该顶点发出的全部有向边.
                                     (3)重复上述两步,直到剩余的网中不再存在没有前趋的顶点为止.

Harry and Magical Computer

 
 Accepts: 408
 
 Submissions: 1622
 Time Limit: 2000/1000 MS (Java/Others)
 
 Memory Limit: 32768/32768 K (Java/Others)
Problem Description

In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins to deal with a process, it will work until the ending of the processes. One day the computer got n processes to deal with. We number the processes from 1 to n. However there are some dependencies between some processes. When there exists a dependencies (a, b), it means process b must be finished before process a. By knowing all the m dependencies, Harry wants to know if the computer can finish all the n processes.

Input

There are several test cases, you should process to the end of file. For each test case, there are two numbers n m on the first line, indicates the number processes and the number of dependencies. 1n100,1m10000 The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b). 1a,bn

Output

Output one line for each test case. If the computer can finish all the process print "YES" (Without quotes). Else print "NO" (Without quotes).

Sample Input
3 23 12 13 33 22 11 3
Sample Output
YESNO


分析:判断是否可以拓扑排序,有向图中是否有环,最简单的拓扑排序算法。
#include <iostream>#include<stdio.h>#include<algorithm>#include<stdlib.h>#include<string.h>#include<stack>using namespace std;int arc[501][501] ;int top ;int used[501] ; // 标记访问过int index[501] ; // 统计入度数组int m , n ;stack<int>st ;bool istopsort(){    int countt = 0 ;    for(int i =1 ; i<= n ; i++){        if(!index[i])            st.push(i);    }    while(!st.empty()){        int tt = st.top() ;        index[tt] -- ;        st.pop() ;         countt ++ ;         for(int i = 1 ; i<=n ;i++)            if(arc[tt][i]){               index[i]-- ;               if(!index[i])                 st.push(i) ;            }    }    if(countt == n)        return 1 ;    else return 0 ;}int main(){    int a,b;    while(scanf("%d%d", &n , &m) != EOF){        memset(arc, 0, sizeof(arc)) ;        memset(index , 0 , sizeof(index)) ;        for(int i =1 ; i<=m ; i++){            scanf("%d%d" , &a , &b) ;            if(!arc[a][b]){                arc[a][b] = 1 ;                index[b] ++ ;}        }        if(istopsort())            cout<<"YES"<<endl;        else cout<<"NO"<<endl;    }    return 0;}


0 0
原创粉丝点击