Facebook
From Sagar, 3 Months ago, written in C++.
Embed
Download Paste or View Raw
Hits: 180
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. int store[10000][10];
  8. int visited[11]={0};
  9. int parent[11]={-1};
  10. int adj[11][11];
  11. int edvis[11][11]={0};
  12. int incurrentdfs[11]={0};
  13. int t=0;
  14. void dfs(int x,int n){
  15.     visited[x]=1;
  16.     incurrentdfs[x]=1;
  17.     for(int j=1;j<=n;j++){
  18.         if(adj[x][j] && !visited[j]){
  19.             edvis[x][j]=1;
  20.             parent[j]=x;
  21.             dfs(j,n);
  22.         }
  23.         else if(adj[x][j] && visited[j] && incurrentdfs[j]){
  24.             edvis[x][j]=1;
  25.            int c=x;
  26.             while(c!=j){
  27.                 store[t][c]=1;
  28.                 c=parent[c];
  29.             }
  30.             store[t][j]=1;
  31.             t++;
  32.         }
  33.         else if(visited[j] && adj[x][j] && !incurrentdfs[j] && !edvis[x][j]){
  34.             edvis[x][j]=1;
  35.             parent[j]=x;
  36.             dfs(j,n);
  37.         }
  38.     }
  39.     incurrentdfs[x]=0;
  40. }
  41. int main() {
  42.  int n,m;
  43.    cin>>n>>m;
  44.         for(int j=0;j<m;j++){
  45.             int a,b;
  46.             cin>>a>>b;
  47.             adj[a][b]=1;
  48.         }
  49.    
  50.     for(int i=1;i<=n;i++){
  51.         if(!visited[i]){
  52.             dfs(i,n);
  53.         }
  54.     }
  55.     int sum=100000;
  56.     int index=-1;
  57.     for(int i=0;i<t;i++){
  58.         int temp=0;
  59.         for(int j=1;j<=n;j++)if(store[i][j])temp=temp+j;
  60.             if(temp<sum){
  61.                 sum=temp;
  62.                 index=i;
  63.             }
  64.     }
  65.     for(int i=1;i<=n;i++)if(store[index][i])cout<<i<<" ";
  66.     // cout<<"hi"<<t<<endl;
  67.     return 0;
  68. }