Cod sursa(job #3256489)

Utilizator ioana3000ioana profir ioana3000 Data 14 noiembrie 2024 18:22:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <vector>
#include <queue>
#define DMAX 1000000
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
vector <int> G[DMAX]; ///list de adiacenta
queue <int> C;
int viz[DMAX]; ///distmin
 /// vatful care il precede pe x pe varful / lantul de lg min sau 0 daca nu are predecesor

void citire();
void BFS(int x);
int main()
{
    int x;
    citire();
    BFS(s);
    for(x = 1; x <= n; x ++)
        fout << viz[x] - 1 << ' ';
    return 0;
}
void citire()
{
    int i, x, y;
    fin >> n >> m >> s;
    for(i = 0; i < m; i ++)
    {
        fin >> x >> y; //arc
        G[x].push_back(y);
    }

}
void BFS(int x)
{
    int i;
    C.push(x);
    viz[x] = 1;
    while(!C.empty())
        {
            x = C.front();
            C.pop();
            ///parcurg vecinii lui x
            for(i = 0; i < G[x].size(); i ++)
                if(!viz[G[x][i]])
            {
                viz[G[x][i]] = 1 + viz[x];
                C.push(G[x][i]);
            }
        }
}