Cod sursa(job #2196304)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 18 aprilie 2018 23:39:43
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define mp make_pair
#define CHECK(x) if(!(x)) return false;
typedef pair<int, int> pii;

#ifdef INFOARENA
#define ProblemName "bfs"
#endif

#define MCONCAT(A, B) A B
#ifdef ProblemName
#define InFile MCONCAT(ProblemName, ".in")
#define OuFile MCONCAT(ProblemName, ".out")
#else
#define InFile "fis.in"
#define OuFile "fis.out"
#endif

const int MAXBUF = 30000000;
char parseBuf[MAXBUF];
char *head;
bool isDigit[255];

void parseInit() {
  int a = fread(parseBuf, 1, MAXBUF, stdin);
  parseBuf[a] = 0;
  head = parseBuf;
  memset(isDigit, 0, sizeof isDigit);
  for (int i = '0'; i <= '9'; ++i)
    isDigit[i] = true;
}

int nextInt() {
  int ans = 0;
  for (; !isDigit[*head]; ++head);
  for (; isDigit[*head]; ++head)
    ans = ans * 10 + (*head) - '0';
  return ans;
}

const int MAXN = 100010;
const int MAXM = 1000010;
int info[MAXM], nxt[MAXM];
int nextNode = 1;
int dst[MAXN];
int G[MAXN];
int Q[MAXN], qs, qe;

void BFS(int s) {
  qs = qe = 0;
  Q[qe++] = s;
  while (qs < qe) {
    int t = Q[qs++];
    for (int it = G[t]; it; it = nxt[it]) {
      int v = info[it];
      if (v == s || dst[v] > 0)
        continue;
      dst[v] = dst[t] + 1;
      Q[qe++] = v;
    }
  }
}

int main() {
  freopen(InFile, "r", stdin);
  freopen(OuFile, "w", stdout);
  parseInit();
  int N = nextInt(), M = nextInt(), S = nextInt();
  while (M--) {
    int a = nextInt(), b = nextInt();
    info[nextNode] = b;
    nxt[nextNode] = G[a];
    G[a] = nextNode;
    ++nextNode;
  }
  BFS(S);
  for (int i = 1; i <= N; ++i)
    printf("%d ", (dst[i] == 0 && i != S) ? (-1) : dst[i]);
  return 0;
}