Cod sursa(job #2307614)

Utilizator AngelEclipseGarleanu Alexandru Stefan AngelEclipse Data 25 decembrie 2018 02:15:04
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

std::ifstream fin("bfs.in");
std::ofstream fout("bfs.out");

int n, m, s;
std::vector < std::vector <int> > graf(100001);
int costuri[100001];
bool viz[100001];
std::queue < int > bfs;
int cc = 0;

int main() {
    fin>>n>>m>>s;

    for(int i = 0; i < m; i++) {
        int node1, node2;
        fin>>node1>>node2;
        graf[node1].push_back(node2);
    }

    bfs.push(s);

    while(!bfs.empty()) {
        int curent = bfs.front();
        bfs.pop();
        
        cc = costuri[curent];

        for(int i = 0; i < graf[curent].size(); i++) {
            if(!viz[graf[curent][i]]) {
                bfs.push(graf[curent][i]);
                costuri[graf[curent][i]] = cc + 1;
                viz[graf[curent][i]] = true;
            } else if(costuri[graf[curent][i]] > cc + 1) {
                bfs.push(graf[curent][i]);
                costuri[graf[curent][i]] = cc + 1;
            }
        }
    }
    
    for(int i = 1; i <= n; i ++) {
        if(costuri[i] == 0 && i != s)
            fout<<-1<<" ";
        else if( i == s )
            fout<<0<<" ";
        else
            fout<<costuri[i]<<" ";
    }

    return 0;
}