Cod sursa(job #1321137)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 18 ianuarie 2015 19:59:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <fstream>
#include <vector>
 
#define Nmax 100100
#define Neighbour Graph[Node][i]
 
using namespace std;
 
vector <int> Graph[Nmax];
int N, Source, Distance[Nmax];
bool used[Nmax];

template <typename T>
struct Node {

    int value;
    Node * next;
    };

template <typename T>
class Queue {

    private:
        Node <T> * first, * last;

    public:
        Queue() {
            first = last = NULL;
            }

        void push(T newElement) {

            Node <T> * p = new Node<T>;
            p->value = newElement;
            p->next = NULL;

            if(last != NULL)
                last->next = p;
            else
                first = p;

            last = p;

            }

        void pop() {

            Node <T> * p = first;

            if(first->next != NULL)
                first = first->next;
            else
                first = last = NULL;

            delete p;

            }

        T front() {
            return first->value;
            }

        T end() {
            return last->value;
            }

        bool empty() {
            return (last == NULL);
            }

};

Queue <int> Q;

void Bfs() {
 
    int i, Node;
 
    Distance[Source] = 1;
    Q.push(Source);
 
    while(!Q.empty()) {
 
        Node = Q.front();
        Q.pop();
 
        for(int i = 0; i < Graph[Node].size(); i++)
            if(Distance[Neighbour] == 0) {
                Distance[Neighbour] = Distance[Node] + 1;
                Q.push(Neighbour);
                }
 
    }
 
}
void Read() {
 
    int x, y, M;
 
    ifstream in("bfs.in");
    in >> N >> M >> Source;
 
    while(M--) {
        in >> x >> y;
        Graph[x].push_back(y);
        }
 
    in.close();
 
}
void Write() {
 
    ofstream out("bfs.out");
 
    for(int i = 1; i <= N; i++)
        out << (Distance[i] == 0 ? -1 : (Distance[i] - 1)) << ' ';
 
    out << '\n';
    out.close();
 
}
int main() {
 
    Read();
    Bfs();
    Write();
 
    return 0;
}