Cod sursa(job #1556723)

Utilizator mihai.constantinConstantin Mihai mihai.constantin Data 25 decembrie 2015 19:06:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int dmax = 100000;
const int dim = 1000000;

struct MUCHIE {int a, b;};
MUCHIE m[dim + 1];
int inc[dmax+1];

int N, M, S;

int C[dmax+1];
int viz[dmax+1];

bool exc(MUCHIE e1, MUCHIE e2)
{
    if(e1.a == e2.a) return e1.b < e2.b;
    else
        return e1.a < e2.a;
}

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

    int i, x, y, first, last;

    scanf("%d %d %d", &N, &M, &S);

    for(i = 1; i <= M; i++)
        scanf("%d %d", &m[i].a, &m[i].b);

    sort(m+1, m+M+1, exc);

    /*for(i = 1; i <= M; i++) printf("%d ", m[i].a);
    printf("%\n");
    for(i = 1; i <= M; i++) printf("%d ", m[i].b);
    printf("\n");*/

    inc[1] = 1;

    for(i = 2; i <= M; i++)
        if(m[i].a != m[i-1].a)
            inc[ m[i].a ] = i;

    //for(i = 1; i <= N; i++) printf("%d ", inc[i]);


    for(i = 1; i <= N; i++) viz[i] = -1;

    first = last = 1;

    //INSEREZ IN COADA NODUL S CU COSTUL 0
    C[1] = S; viz[S] = 0;

    while(first <= last)
    {
        x = C[first];

        /*
        //PARCURGEM LISTA VECINILOR y AI LUI x

        p = lst[x];

        while(p)
        {
            y = vf[p];

            if(viz[y] == -1)
            {
                last++;
                C[last] = y;
                viz[y] = 1 + viz[x];
            }

            p = urm[p];
        }*/

        //PARCURG LISTA VECINILOR LUI x
        for(i = inc[x]; m[i].a == x; i++)
            if(viz[ m[i].b ] == -1)
            {
                last++;
                C[last] = m[i].b;
                viz[ m[i].b ] = 1 + viz[x];
            }

        first++;
    }

    for(i = 1; i <= N; i++) printf("%d ", viz[i]);

    return 0;
}