সোমবার, ১২ মার্চ, ২০১৮

Detect a cycle using DFS

///...................SUBHASHIS MOLLICK...................///
///.....DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING....///
///.............ISLAMIC UNIVERSITY,BANGLADESH.............///
///....................SESSION-(14-15)....................///
#include<bits/stdc++.h>
using namespace std;
#define sf(a) scanf("%lld",&a)
#define sf2(a,b) scanf("lld",&a,&b)
#define sf3(a,b,c) scanf("lld%lld",&a,&b,&c)
#define pf(a) printf("%lld",a)
#define pf2(a,b) printf("lld",a,b)
#define pf3(a,b,c) printf("lld%lld",a,b,c)
#define nl printf("\n")
#define ll long long
#define pb push_back
#define MPI map<int,int>mp
#define fr(i,n) for(i=0;i<n;i++)
#define fr1(i,n) for(i=1;i<=n;i++)
#define frl(i,a,b) for(i=a;i<=b;i++)
//freopen("Input.txt","r",stdin);
//freopen("Output.txt","w",stdout);
#define M 100005
long visited[M], cycle = 0;
vector<long> edge[M];
void visit( long p )
{
    if( visited[p] == 2 || cycle )
        return;
    // we won't process anything if we already have found a cycle
    if( visited[p] == 1 )
    {
        cycle = 1; // found cycle
        return;
    }

    visited[p] = 1;
    for(long i=0; i<edge[p].size(); i++)
        visit( edge[p][i] );
    visited[p] = 2;
}
main()
{
    long n,m,q;
    while(cin>>n>>m>>q)
    {
        long i,u,v;
        for(i=1; i<=m; i++)
        {
            cin>>u>>v;
            edge[u].push_back(v);
        }
        cycle=0;
        visit(q);
        if(cycle==1)
        {
            printf("yes\n");
        }
        else
            printf("no\n");
        for(i=1; i<=m; i++)
        {
            edge[i].clear();
            visited[i]=0;
        }
    }
}

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন

Factory Pattern

Factory Method  is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alte...