YEZAELP

SMMR-153: Food Web

Jun 7th, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int color[100001];
  4. vector <int> g[100001];
  5. bool cycle=false;
  6. void dfs(int u){
  7.     if(color[u]==1) {
  8.         cycle=true;
  9.         return ;
  10.     }
  11.     if(color[u]==2){
  12.         return ;
  13.     }
  14.     color[u]=1;
  15.     for(auto v:g[u]){
  16.         dfs(v);
  17.     }
  18.     color[u]=2;
  19. }
  20. int main(){
  21.     int n,m;
  22.     scanf("%d %d",&n,&m);
  23.     int head[n+1];
  24.     vector <int> parent[n+1];
  25.  
  26.     for(int i=0;i<=n;i++){
  27.         head[i]=0;
  28.     }
  29.     for(int i=1;i<=m;i++){
  30.         int u,v;
  31.         scanf("%d %d",&u,&v);
  32.         g[v].push_back(u);
  33.         parent[u].push_back(v);
  34.         head[u]++;
  35.     }
  36.  
  37.  
  38.     for(int i=1;i<=n;i++){
  39.         if(color[i]==0){
  40.             dfs(i);
  41.             if(cycle){
  42.                 printf("No");
  43.                 return 0;
  44.             }
  45.         }
  46.     }
  47.  
  48.     printf("Yes\n");
  49.     queue <int> q;
  50.     vector <bool> visited(n+1,false);
  51.     for(int i=1;i<=n;i++){//head[i]=0;
  52.         if(head[i]==0) q.push(i);
  53.     }
  54.     while(!q.empty()){
  55.         int u;
  56.         u=q.front();
  57.         q.pop();
  58.  
  59.         if(visited[u]) continue;
  60.         bool con=true;
  61.         for(auto pr:parent[u]){
  62.             if(!visited[pr]) con=false;
  63.         }
  64.  
  65.         if(con==false) continue;
  66.         visited[u]=true;
  67.         printf("%d ",u);
  68.         for(auto v:g[u]){
  69.             if(!visited[v]) {
  70.                 q.push(v);
  71.             }
  72.         }
  73.     }
  74.  
  75.  
  76.     return 0;
  77. }
Add Comment
Please, Sign In to add comment