Cod sursa(job #1371269)

Utilizator RazzinnatorRazvan Brinzea Razzinnator Data 3 martie 2015 20:15:57
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <vector>
#include <stdio.h>
#include <queue>

using namespace std;

FILE *f = fopen( "bfs.in", "r" );
FILE *g = fopen( "bfs.out", "w" );

int cost[100005];

int main()
{
    int n, m, s;
    vector<int> empty_list;
    queue<int> q;

    /* read data, initialize graph */
    fscanf( f, "%d%d%d", &n, &m, &s );
    vector< vector<int> > graf( n+1, empty_list );
    for( int i = 0; i < m; i++ )
    {
        int x,y;
        fscanf( f, "%d%d", &x, &y );
        graf[x].push_back(y);
    }

    q.push( s );
    while( !q.empty() )
    {
        int current_node = q.front();
        for( int i = 0; i < graf[current_node].size(); i++ )
        {
            vector<int> current_list = graf[current_node];
            if( cost[ current_list[i] ] == 0 && current_list[i] != s )
            {
                q.push( current_list[i] );
                cost[ current_list[i] ] = cost[current_node] + 1;
            }
        }
        q.pop();
    }

    for( int i = 1; i <= n; i++ )
    {
        if( i == s )
        {
            fprintf( g, "%d ", 0 );
        }
        else if( cost[i] == 0 )
        {
            fprintf( g, "%d ", -1 );
        }
        else
        {
            fprintf( g, "%d ", cost[i] );
        }
    }

    fprintf( g, "\n" );
    fclose( f );
    fclose( g );

    return 0;
}