# G - Topological Sorting URAL - 1280(拓扑排序）

2017-12-11 18:50:18来源:CSDN作者:Fusheng_Yizhao人点击

``Michael wants to win the world championship in programming and decided to study N subjects (for convenience we will number these subjects from 1 to N). Michael has worked out a study plan for this purpose. But it turned out that certain subjects may be studied only after others. So, Michael’s coach analyzed all subjects and prepared a list of M limitations in the form “ si ui” (1 ≤ si, ui ≤ N; i = 1, 2, …, M) , which means that subject si must be studied before subject ui.Your task is to verify if the order of subjects being studied is correct.Remark. It may appear that it’s impossible to find the correct order of subjects within the given limitations. In this case any subject order worked out by Michael is incorrect.Limitations1 ≤ N ≤ 1000; 0 ≤ M ≤ 100000.``

Input
The first line contains two integers N and M ( N is the number of the subjects, M is the number of the limitations). The next M lines contain pairs si, ui, which describe the order of subjects: subject si must be studied before ui. Further there is a sequence of N unique numbers ranging from 1 to N — the proposed study plan.
Output
Output a single word “YES” or “NO”. “YES” means that the proposed order is correct and has no contradictions with the given limitations. “NO” means that the order is incorrect.
Example
input

``5 61 31 43 55 24 21 21 3 4 5 2``

output

``YES``

input
5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 2 4 5 3

output

``NO``

``#include<stdio.h>#include<stdlib.h>#include<string.h>int mapp[1010][1010];int tp[1010];int main(){    int n,m,i,j;    int t[1010];    while(~scanf("%d %d",&n,&m))    {        memset(mapp,0,sizeof(mapp));        memset(tp,0,sizeof(tp));        for(i=0;i<m;i++)        {            int u,v;            scanf("%d %d",&u,&v);            if(mapp[u][v]==0)///重边                tp[v]++;            mapp[u][v] = 1;        }        for(i=1;i<=n;i++)        {            scanf("%d",&t[i]);        }        int flag = 1;        for(i=1;i<=n;i++)        {            if(tp[t[i]]!=0)                flag  = 0;            for(j=1;j<=n;j++)            {                if(mapp[t[i]][j])                    tp[j]--;            }        }        if(flag) printf("YES/n");        else printf("NO/n");    }    return 0;}``