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

Envío 2591

Problema 0x53 - Encontrar ciclos en un grafo dirigido

Caso # Resultado Tiempo Memoria
#1
Correcto
0.006 s 2 KBi
#2
Correcto
0.005 s 2 KBi
#3
Correcto
0.007 s 14 KBi
#4
Correcto
0.006 s 18 KBi
#5
Correcto
0.005 s 2 KBi
#6
Correcto
0.007 s 2 KBi
#7
Correcto
0.007 s 2 KBi
#8
Correcto
0.005 s 1 KBi
#9
Correcto
0.01 s 1 KBi
#10
Correcto
0.007 s 2 KBi
#11
Correcto
0.005 s 2 KBi
#12
Correcto
0.005 s 8 KBi
#13
Correcto
0.006 s 2 KBi
#14
Correcto
0.007 s 21 KBi
#15
Correcto
0.005 s 23 KBi
#16
Correcto
0.004 s 2 KBi
#17
Correcto
0.006 s 16 KBi
#18
Correcto
0.006 s 2 KBi
#19
Correcto
0.005 s 2 KBi
#20
Correcto
0.006 s 2 KBi
#21
Correcto
0.008 s 1 KBi
#22
Correcto
0.006 s 29 KBi
#23
Correcto
0.005 s 11 KBi
#24
Correcto
0.006 s 2 KBi
#25
Correcto
0.006 s 1 KBi
#26
Correcto
0.011 s 2 KBi
#27
Correcto
0.08 s 3 KBi
#28
Correcto
0.015 s 2 KBi
#29
Correcto
0.07 s 3 KBi
#30
Correcto
0.012 s 2 KBi
#31
Correcto
0.017 s 2 KBi
#32
Correcto
0.051 s 2 KBi
#33
Correcto
0.024 s 5 KBi
#34
Correcto
0.022 s 3 KBi
#35
Correcto
0.062 s 5 KBi
Puntos totales: 100 / 100

Código

#include <bits/stdc++.h>

#include <queue>
#include <vector>

using namespace std;

struct Node {
  int val;
  vector<int> neighbors;
  Node(int x) : val(x) {}
};

bool helper(int index, vector<Node *> &lookup, vector<bool> &visited,
            vector<bool> &visitedOrder) {
  if (visited[index] == false) {
    visited[index] = true;
    visitedOrder[index] = true;

    auto neighbors =  lookup[index]->neighbors;
    for (int i = 0; i < neighbors.size(); ++i) {
        auto neighborIndex = neighbors[i];
        auto neighbor = lookup[neighborIndex];

        if (visited[neighborIndex] == false and helper(neighborIndex, lookup, visited, visitedOrder)){
            return true;
        } else if (visitedOrder[neighborIndex]) {
            return true;
        }
    }
  }
  visitedOrder[index] = false;
  return false;
}

bool check_cyclic(vector<Node *> &lookup) {
  vector<bool> visited(lookup.size(), false);
  vector<bool> visitedOrder(lookup.size(), false);
  for (int i = 0; i < lookup.size(); i++) {
    if (helper(i, lookup, visited, visitedOrder)) {
      return true;
    }
  }
  return false;
}

int main() {
  int n, m;
  cin >> n >> m;
  vector<Node *> lookup(n);
  for (int i = 0; i < n; i++) {
    lookup[i] = new Node(i);
  }
  for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    lookup[u]->neighbors.push_back(v);
  }
  if (check_cyclic(lookup)) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
  return 0;
}