Cod sursa(job #2427600)

Utilizator lukapopoviciNUme Fals lukapopovici Data 1 iunie 2019 03:54:00
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>

#include<vector>

#include<queue>

#include<fstream>

#include <algorithm>    // std::sort

using namespace std;

ifstream in("bfs.in");

ofstream out("bfs.out");

int c=0;

queue<int> rez;

struct graph

{

    int info;

    std::vector<int> q;

    bool viz;

};

graph GRAF[1000000];

void citire(int n,int &max1)

{

    int i=1;

    int a=0;

    int b=0;

    for(i=1; i<=n; i++)

    {

        in>>a>>b;

        GRAF[a].q.push_back(b);

        if(max(a,b)>max1)

            max1=max(a,b);

    }



}

void siguranta(int n)

{

    int i=0;

    for(i; i<=n; i++)

          std::sort (GRAF[i].q.begin(),GRAF[i].q.end());

}

void BFS(int n)

{

    rez.push(n);

    queue<int> p;

    GRAF[n].viz=1;

    GRAF[n].info=0;

    p.push(n);

    while(!p.empty())

    {

        int x=p.front();

        p.pop();

        int len=GRAF[x].q.size()-1;

        for(int i=0; i<=len; i++)

        {

            if(GRAF[GRAF[x].q[i]].viz==0)

            {

                p.push(GRAF[x].q[i]);

              GRAF[GRAF[x].q[i]].info=1+GRAF[x].info;

                GRAF[GRAF[x].q[i]].viz=1;

                c++;

            }

        }

    }

}

void rect(int n,int max){

for(int i=1;i<=max;i++)

    if(GRAF[i].info==0 && i!=n)

    GRAF[i].info=-1;

}

    int main()

    {

        int n;

        int o;

        int m;

        in>>o;

        in>>n;

        in>>m;

        int max=0;

        citire(n,max);

        siguranta(n);

        BFS(m);

        rect(m,max);

     for(int o=1;o<=max;o++)

        out<<GRAF[o].info<<" ";

    }