█████████ ████ ███░░░░░███ ░░███ ███ ░░░ ██████ ███████ ██████ ██████ ░███ ███░░███ ███░░███ ███░░███ ███░░███ ░███ ░███ ░███░███ ░███ ░███████ ░███ ░███ ░░███ ███░███ ░███░███ ░███ ░███░░░ ░███ ░███ ░░█████████ ░░██████ ░░████████░░██████ ░░██████ ░░░░░░░░░ ░░░░░░ ░░░░░░░░ ░░░░░░ ░░░░░░

Envío 2549

Problema 0x53 - Encontrar ciclos en un grafo dirigido

  • Autor: judavid.arias
  • Fecha: 2021-01-02 16:46:13 UTC (Hace casi 2 años)
Caso # Resultado Tiempo Memoria
#1
Correcto
0.005 s 3 KBi
#2
Correcto
0.004 s 1 KBi
#3
Correcto
0.007 s 2 KBi
#4
Correcto
0.008 s 2 KBi
#5
Correcto
0.006 s 2 KBi
#6
Correcto
0.007 s 1 KBi
#7
Correcto
0.005 s 2 KBi
#8
Correcto
0.005 s 16 KBi
#9
Correcto
0.007 s 15 KBi
#10
Correcto
0.005 s 2 KBi
#11
Correcto
0.007 s 2 KBi
#12
Correcto
0.005 s 30 KBi
#13
Correcto
0.004 s 1 KBi
#14
Correcto
0.007 s 14 KBi
#15
Correcto
0.005 s 2 KBi
#16
Correcto
0.005 s 2 KBi
#17
Correcto
0.005 s 3 KBi
#18
Correcto
0.005 s 1 KBi
#19
Correcto
0.004 s 2 KBi
#20
Correcto
0.005 s 1 KBi
#21
Correcto
0.006 s 1 KBi
#22
Correcto
0.006 s 1 KBi
#23
Correcto
0.006 s 2 KBi
#24
Correcto
0.006 s 6 KBi
#25
Correcto
0.005 s 1 KBi
#26
Correcto
0.005 s 2 KBi
#27
Correcto
0.046 s 2 KBi
#28
Correcto
0.009 s 20 KBi
#29
Correcto
0.05 s 2 KBi
#30
Correcto
0.009 s 13 KBi
#31
Correcto
0.01 s 2 KBi
#32
Correcto
0.047 s 2 KBi
#33
Correcto
0.017 s 2 KBi
#34
Correcto
0.017 s 3 KBi
#35
Correcto
0.052 s 3 KBi
Puntos totales: 100 / 100

Código

#include <iostream>
#include<bits/stdc++.h> 
#include <vector>

using namespace std; 

void addEdge(vector<int> adj[], int u, int v){
	adj[u].push_back(v);
}
 

bool isCyclicUtil(vector<int> adj[], int v, bool visited[], bool *recStack) 
{ 
    if(visited[v] == false) 
    { 
        // Mark the current node as visited and part of recursion stack 
        visited[v] = true; 
        recStack[v] = true; 
  
        // Recur for all the vertices adjacent to this vertex 
        vector<int>::iterator i; 
        for(i = adj[v].begin(); i != adj[v].end(); ++i) 
        { 
            if ( !visited[*i] && isCyclicUtil(adj, *i, visited, recStack) ) 
                return true; 
            else if (recStack[*i]) 
                return true; 
        } 
  
    } 
    recStack[v] = false;  // remove the vertex from recursion stack 
    return false; 
} 

bool bfs(vector<int> adj[], int V){
	bool *visited = new bool[V];
	bool *recStack = new bool[V];
	for(int i =0;i<V;i++){
		visited[i] = false;
		recStack[i] = false;
	}
	
	for(int i = 0; i < V; i++) 
        if (isCyclicUtil(adj, i, visited, recStack)) 
            return true; 
  
    return false; 
	
}

int main() {
	int N, M;
	cin >> N;
	cin >> M;
    vector<int> adj[N]; 
    for(int i = 0; i < M ;i++){
    	int u,v;
    	cin >> u;
    	cin >> v;
    	addEdge(adj, u, v); 
	}
	 bool res =  bfs(adj, N);
	 if(res == 1)
    	cout << "Yes" << endl;
    else
    	cout << "No" << endl;
    return 0; 
}