首页 > 代码库 > URAL(timus) 1280 Topological Sorting(模拟)
URAL(timus) 1280 Topological Sorting(模拟)
Topological Sorting
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
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.
Limitations
1 ≤ N ≤ 1000; 0 ≤ M ≤ 100000.
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.
Samples
input | output |
---|---|
5 61 31 43 55 24 21 21 3 4 5 2 | YES |
5 61 31 43 55 24 21 21 2 4 5 3 | NO |
#include <iostream>#include <cstring>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <time.h>#include <string>#include <map>#include <stack>#include <vector>#include <set>#include <queue>#define inf 10000000#define mod 10000typedef long long ll;using namespace std;const int N=1005;const int M=100005;int power(int a,int b,int c){int ans=1;while(b){if(b%2==1){ans=(ans*a)%c;b--;}b/=2;a=a*a%c;}return ans;}int in[N],vis[N],w[N][N];int n,m,k;vector<int>vec[N];int main(){ int a,b; bool flag=true; scanf("%d%d",&n,&m); while(m--){ scanf("%d%d",&a,&b); if(!w[a][b]){ w[a][b]=1; vec[a].push_back(b); } } for(int i=1;i<=n;i++){ scanf("%d",&in[i]); } for(int i=1;i<=n;i++){ int cnt=0; for(int j=i+1;j<=n;j++){ if(w[in[i]][in[j]])cnt++; } if(cnt!=vec[in[i]].size())flag=false; } if(flag)printf("YES\n"); else printf("NO\n"); return 0;}
URAL(timus) 1280 Topological Sorting(模拟)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。