Cod sursa(job #2227450)

Utilizator inquisitorAnders inquisitor Data 31 iulie 2018 19:38:07
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <stdio.h>
#include <string.h>
#include <malloc.h>

#pragma GCC optimize("O1")

int *Graph[100001], degree[100001], level[100001];

void BFS(int start)
{
    int queue[100001], left = 0, right = 0, *child;

    level[queue[0] = start] = 1;

    for(; left <= right; ++left)
    {
        for(child = Graph[queue[left]] + 1; *child != -1; ++child)
        {
            if(!level[*child])
            {
                queue[++right] = *child;

                level[*child] = level[queue[left]] + 1;
            }
        }
    }
}

char buffer[20000000]; int p = -1;

__attribute__((always_inline)) int get_int()
{
    int number = 0;

    for(++p; buffer[p] > 47; ++p)
    {
        number = number * 10 + buffer[p] - 48;
    }

    return number;
}

__attribute__((always_inline)) void pass_int()
{
    for(++p; buffer[p] > 47; ++p);
}

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

    fread(buffer, 1, 20000000, stdin);

    int N = get_int(), M = get_int(), start = get_int();

    for(int i = 1; i <= M; i++)
    {
        ++degree[get_int()];

        pass_int();
    }

    for(int i = 1; i <= N; ++i)
    {
        Graph[i] = (int*)malloc((degree[i] + 2) * sizeof(int));

        Graph[i][degree[i] + 1] = -1;

        degree[i] = 0;
    }

    p = -1; pass_int(), pass_int(), pass_int();

    for(int i = 1; i <= M; i++)
    {
        int u = get_int();

        Graph[u][++degree[u]] = get_int();
    }

    BFS(start);

    for(int i = 1; i <= N; i++)
    {
        printf("%d ", level[i] - 1);
    }

    return 0;
}