Cod sursa(job #1309004)

Utilizator deea101Andreea deea101 Data 5 ianuarie 2015 01:40:06
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#define NMAX 100001
#include <cstring>

#include <fstream>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");


struct node
{
    int key; 
    node *next;
    node()
    {
            next=NULL;
    }
};

class List
{
    private:
        node *first,*last;
    public:
        List()
        {
			first=last=NULL;
        }
        node *front()
        {
           return first;
        }
        void push_back(int key)
        {
			node *p;
			p=new node;
			p->key=key;

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

class queue
{
    private:
		node *first,*last;
		
    public:
        queue()
        {
			first=last=NULL;
        }
        int front()
        {
           if(first!=NULL) return first->key;
        }
        bool empty()
        {
           if(first==NULL) return 1;
           else return 0;
        }
        void pop()
        {
			node *p=first;
			first=first->next;
			delete p;
        }
        void push(int x)
        {
			node *p;
            p=new node;
			p->key=x;
		
			if(first==NULL)
				first=p;
			else last->next=p;
			last=p;
        }
};
class Graph
{
    private:
            int N,components,comp[NMAX];
            List v[NMAX];
            bool visited[NMAX];

    public:
        int dist[NMAX];
		Graph()
		{
			memset(v,NULL,sizeof(v));
			memset(comp,0,sizeof(comp));
			memset(visited,0,sizeof(visited));
			memset(dist,-1,sizeof(dist));
		}
		void setSize(int n)
		{
			N=n;
		}
		void addEdge(int i, int j)
		{
			v[i].push_back(j);
		}
         
        void bfs(int Node)
        {
            queue q;
            int x;
            node *p;
            q.push(Node);
            while(!q.empty())
            {
                x=q.front();
                q.pop();
                visited[x]=1;
                
                p=v[x].front();
                while(p!=NULL)
				{
                    if(!visited[p->key]) 
					{
						q.push(p->key);
						if(dist[x]+1<dist[p->key] || dist[p->key]==-1) 
							dist[p->key]=dist[x]+1;
					}
					p=p->next;
				}
            }
        }
        void getDist(int S)
        {
            dist[S]=0;
            bfs(S);
            for(int i=1;i<=N;i++) g<<dist[i]<<' ';
        }
}G;

int main()
{
	int N,M,S;
	f>>N>>M>>S;
	G.setSize(N);
	int x,y;
	while(M--)
	{
		f>>x>>y;
		G.addEdge(x,y);
	}
	G.getDist(S);
}