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

Envío 2519

Problema 0x53 - Encontrar ciclos en un grafo dirigido

  • Autor: andreslel
  • Fecha: 2020-12-29 19:20:52 UTC (Hace casi 4 años)
Caso # Resultado Tiempo Memoria
#1
Correcto
0.006 s 35 KBi
#2
Correcto
0.005 s 2 KBi
#3
Correcto
0.006 s 2 KBi
#4
Correcto
0.006 s 2 KBi
#5
Correcto
0.005 s 2 KBi
#6
Correcto
0.006 s 1 KBi
#7
Correcto
0.005 s 2 KBi
#8
Correcto
0.007 s 2 KBi
#9
Correcto
0.006 s 1 KBi
#10
Correcto
0.005 s 1 KBi
#11
Correcto
0.005 s 1 KBi
#12
Correcto
0.005 s 2 KBi
#13
Correcto
0.004 s 1 KBi
#14
Correcto
0.004 s 1 KBi
#15
Correcto
0.005 s 2 KBi
#16
Correcto
0.006 s 22 KBi
#17
Correcto
0.006 s 1 KBi
#18
Correcto
0.004 s 2 KBi
#19
Correcto
0.006 s 15 KBi
#20
Correcto
0.008 s 2 KBi
#21
Correcto
0.006 s 5 KBi
#22
Correcto
0.005 s 1 KBi
#23
Correcto
0.006 s 1 KBi
#24
Correcto
0.006 s 18 KBi
#25
Correcto
0.005 s 1 KBi
#26
Correcto
0.008 s 17 KBi
#27
Correcto
0.058 s 3 KBi
#28
Correcto
0.008 s 12 KBi
#29
Correcto
0.052 s 2 KBi
#30
Correcto
0.009 s 2 KBi
#31
Correcto
0.017 s 17 KBi
#32
Correcto
0.076 s 2 KBi
#33
Correcto
0.021 s 3 KBi
#34
Correcto
0.025 s 3 KBi
#35
Correcto
0.09 s 3 KBi
Puntos totales: 100 / 100

Código

#include<bits/stdc++.h>
using namespace std;

vector<int> seen;
vector<int> topo;
void dfs(int from, vector<vector<int>> &G){
    seen[from] = 1;
    for(auto adj:G[from])
        if(!seen[adj])
            dfs(adj,G);
}

void topoSort(int from,vector<vector<int>> &G){
    seen[from] = 1;
    for(auto adj:G[from])
        if(!seen[adj])
            topoSort(adj,G);
    topo.push_back(from);
}

int main(){
    int n,m;
    scanf(" %d %d",&n,&m);
    seen.resize(n,0);
    vector<vector<int>> G(n),GI(n);
    int already = 0;
    while(m--){
        int a,b;
        scanf(" %d %d",&a,&b);
        GI[b].push_back(a);
        G[a].push_back(b);
        already = already | (a == b);
    }
    if(already){
        puts("Yes");
        return 0;
    }
    for(int i = 0; i < n;++i)
        if(!seen[i])
            topoSort(i,GI);
    reverse(topo.begin(),topo.end());
    seen.clear();
    seen.resize(n,0);
    int components = 0;
    for(auto va:topo)
        if(!seen[va]){
            dfs(va,G);
            ++components;
        }
    if(components == n)
        puts("No");
    else puts("Yes");
    return 0;
}