Topological Sorting

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, uiN; 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.
Limitations
1 ≤ 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 output
5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 3 4 5 2
YES
5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 2 4 5 3
NO


AC代码(记下每一个数字的位置对比就ok了)

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main()
{
    int s[100000+10], u[100000+10], i,  a[1000+10], x;
    int n, m, f;
    while(cin>>n>>m)
    {
      f = 1;
     for(i = 1;i<=m;i++)
     {
      cin>>s[i]>>u[i];
     }
     for(i = 1;i<=n;i++)
     {
      cin>>x;
      a[x] = i;
     }
     for(i = 1;i<=m;i++)
     {
      if(a[s[i]]>a[u[i]])
      {
       f = 0;
       break;
      }
     }
     if(f==0)
     printf("NO\n");
     else
     printf("YES\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41524782/article/details/80739090