Cod sursa(job #3264932)

Utilizator Manolea_Teodor_StefanManolea Teodor Stefan Manolea_Teodor_Stefan Data 25 decembrie 2024 20:13:28
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx2,bmi,bmi2,popcnt,lzcnt")

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int nmax = 100001;

int n,m,q;
array<vector<int>,nmax> g;
int ans[nmax];
bool vis[nmax];

struct cv {
    int x;
    int len;
    friend bool operator<(const auto& A, const auto& B) {
        return A.len > B.len;
    }
};

priority_queue<cv> pq;

int main() {
    fin >> n >> m >> q;
    while (m--) {
        int a,b;
        fin >> a >> b;
        g[a].push_back(b);
    }
    for (int i = 1; i <= n; i++) {
        ans[i] = -1;
    }
    for (const auto y : g[q]) {
        if (y == q) {
            continue;
        }
        pq.push({y,1});
    }
    ans[q] = 0;
    vis[q] = 1;
    while (!pq.empty()) {
        const auto temp = pq.top();
        pq.pop();
        if (!vis[temp.x]) {
            vis[temp.x] = 1;
            ans[temp.x] = temp.len;
            for (const auto y : g[temp.x]) {
                if (!vis[y]) {
                    pq.push({y,temp.len + 1});
                }
            }
        }
    }

    for (int i = 1; i <= n; i++) {
        fout << ans[i] << ' ';
    }

    return 0;
}