{ }codelper
BFSqueueP0291

The museum whose doors lock one by one

A museum has n rooms numbered 1 to n. There are m corridors, and a corridor "a b" joins room a and room b. Corridors can be walked both ways, and walking one corridor takes 1 minute. Several corridors may join the same two rooms. The museum is closing, so the room entrances lock one by one. Room i can be entered up to minute tᵢ.
Arriving exactly at minute tᵢ is allowed, and arriving later is not. After an entrance locks, a person already inside can still leave at any time. One visitor is inside room 1 at minute 0. The visitor starts in room 1, so room 1 counts as entered at minute 0 whatever t₁ is. The visitor moves only along corridors, and passing through a room means entering it. For every room, find the earliest minute at which the visitor can enter it. A room that cannot be entered by any route has the value -1. On the first line print the number of rooms that can be entered.
Room 1 is counted too. On the second line print the values of rooms 1 to n in order, separated by single spaces.

Input
The first line has n and m, the second line t₁ … tₙ, and each of the next m lines has a and b.
Numbers on a line are separated by one space.
1 ≤ n ≤ 10,000, 0 ≤ m ≤ 20,000, 0 ≤ tᵢ ≤ 10,000, 1 ≤ a, b ≤ n, a ≠ b.
All are integers
Output
Line 1: the number of rooms that can be entered.
Line 2: the earliest minute for each of the n rooms, or -1 if it cannot be entered
Example 1 · stdin
6 6
5 1 1 3 2 9
1 2
2 3
1 4
4 5
5 3
3 6
stdout
4
0 1 -1 1 2 -1
Example 2 · stdin
4 3
0 1 2 3
1 2
2 3
3 4
stdout
4
0 1 2 3
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Breadth-first search (BFS) takes rooms out of the queue from nearest to farthest, so the first time you reach a room is the earliest time.
If it is already locked then, it is still locked later, so one check t ≤ tᵥ at the moment of reaching is enough.
First example: room 3 is reached through room 2 at minute 2, but t₃ = 1 so it cannot be entered (through room 5 it would be minute 3), and so room 6 has no route even though t₆ = 9 is generous.
Trap one: ignoring the doors, computing all distances first and then keeping the rooms with distance ≤ t is wrong — distances that go through a locked room get mixed in, and room 6 of the first example comes out as 3.
Trap two: writing t < tᵥ misses a room reached exactly at minute tᵥ (second example).
Trap three: looking at the t of the room you leave is wrong — leaving is still possible after the lock.
Trap four: taking from a stack (last in, first out) instead of a queue turns it into depth-first search, which reaches rooms by a roundabout route first, and that later time gets the door locked.
Trap five: corridors go both ways, so add both directions to the adjacency lists.
Trap six: the count on the first line includes room 1.
Queues differ by language: Python uses popleft() of collections.deque (pop(0) on a list shifts everything behind it, which is slow), Java ArrayDeque, C# Queue<int>, C++ std::queue.
shift() on a JavaScript/TypeScript array also shifts the rest, so only push and read with a moving head index.
In C each room enters the queue once, so an n-slot array with head and tail indices is enough.
Craykon also adds to a list with Add and moves a head index, and walks the neighbours with foreach (v in halls[u]).

Pythonmain.py · 29 lines
import sysfrom collections import deque data = sys.stdin.read().split()n, m = int(data[0]), int(data[1])close = [0] + [int(x) for x in data[2:2 + n]]  # close[v] = v번 전시실에 들어갈 수 있는 마지막 시각 # 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)halls = [[] for _ in range(n + 1)]for i in range(m):    a, b = int(data[2 + n + 2 * i]), int(data[3 + n + 2 * i])    halls[a].append(b)    halls[b].append(a) # 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다arrive = [-1] * (n + 1)arrive[1] = 0  # 1번에는 처음부터 있으니 close[1]은 보지 않는다queue = deque([1])while queue:    u = queue.popleft()    t = arrive[u] + 1  # 이웃 전시실에 닿는 시각    for v in halls[u]:        # 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다        if arrive[v] == -1 and t <= close[v]:            arrive[v] = t            queue.append(v) print(sum(1 for v in range(1, n + 1) if arrive[v] != -1))print(" ".join(map(str, arrive[1:])))
JavaScriptmain.js · 35 lines
const data = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const n = data[0];const m = data[1];// close[v] = v번 전시실에 들어갈 수 있는 마지막 시각const close = [0];for (let v = 1; v <= n; v++) close.push(data[1 + v]); // 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)const halls = Array.from({ length: n + 1 }, () => []);for (let i = 0; i < m; i++) {  const a = data[2 + n + 2 * i];  const b = data[3 + n + 2 * i];  halls[a].push(b);  halls[b].push(a);} // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다const arrive = new Array(n + 1).fill(-1);arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다const queue = [1];// shift()는 뒤의 것을 모두 당겨서 느리다. 머리 번호 head를 옮긴다for (let head = 0; head < queue.length; head++) {  const u = queue[head];  const t = arrive[u] + 1; // 이웃 전시실에 닿는 시각  for (const v of halls[u]) {    // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다    if (arrive[v] === -1 && t <= close[v]) {      arrive[v] = t;      queue.push(v);    }  }} console.log(queue.length); // 큐에 한 번씩 들어간 전시실이 곧 들어갈 수 있는 전시실이다console.log(arrive.slice(1).join(" "));
TypeScriptmain.ts · 37 lines
import { readFileSync } from "node:fs"; const data: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const n = data[0];const m = data[1];// close[v] = v번 전시실에 들어갈 수 있는 마지막 시각const close: number[] = [0];for (let v = 1; v <= n; v++) close.push(data[1 + v]); // 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)const halls: number[][] = Array.from({ length: n + 1 }, (): number[] => []);for (let i = 0; i < m; i++) {  const a = data[2 + n + 2 * i];  const b = data[3 + n + 2 * i];  halls[a].push(b);  halls[b].push(a);} // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다const arrive: number[] = new Array<number>(n + 1).fill(-1);arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다const queue: number[] = [1];// shift()는 뒤의 것을 모두 당겨서 느리다. 머리 번호 head를 옮긴다for (let head = 0; head < queue.length; head++) {  const u = queue[head];  const t = arrive[u] + 1; // 이웃 전시실에 닿는 시각  for (const v of halls[u]) {    // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다    if (arrive[v] === -1 && t <= close[v]) {      arrive[v] = t;      queue.push(v);    }  }} console.log(queue.length); // 큐에 한 번씩 들어간 전시실이 곧 들어갈 수 있는 전시실이다console.log(arrive.slice(1).join(" "));
JavaMain.java · 54 lines
import java.io.*;import java.util.*; public class Main {    public static void main(String[] args) throws IOException {        StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));        st.nextToken();        int n = (int) st.nval;        st.nextToken();        int m = (int) st.nval;        int[] close = new int[n + 1]; // close[v] = v번 전시실에 들어갈 수 있는 마지막 시각        for (int v = 1; v <= n; v++) {            st.nextToken();            close[v] = (int) st.nval;        }         // 인접 목록: halls.get(v) = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)        List<List<Integer>> halls = new ArrayList<>();        for (int v = 0; v <= n; v++) halls.add(new ArrayList<>());        for (int i = 0; i < m; i++) {            st.nextToken();            int a = (int) st.nval;            st.nextToken();            int b = (int) st.nval;            halls.get(a).add(b);            halls.get(b).add(a);        }         // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다        int[] arrive = new int[n + 1];        Arrays.fill(arrive, -1);        arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다        ArrayDeque<Integer> queue = new ArrayDeque<>();        queue.add(1);        int reached = 1;        while (!queue.isEmpty()) {            int u = queue.poll();            int t = arrive[u] + 1; // 이웃 전시실에 닿는 시각            for (int v : halls.get(u)) {                // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다                if (arrive[v] == -1 && t <= close[v]) {                    arrive[v] = t;                    queue.add(v);                    reached++;                }            }        }         StringBuilder sb = new StringBuilder();        sb.append(reached).append('\n');        for (int v = 1; v <= n; v++) sb.append(arrive[v]).append(v < n ? ' ' : '\n');        System.out.print(sb);    }}
C#Main.cs · 52 lines
using System;using System.Collections.Generic;using System.Text; class Program{    static void Main()    {        var data = Console.In.ReadToEnd().Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);        int n = int.Parse(data[0]), m = int.Parse(data[1]);        var close = new int[n + 1]; // close[v] = v번 전시실에 들어갈 수 있는 마지막 시각        for (int v = 1; v <= n; v++) close[v] = int.Parse(data[1 + v]);         // 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)        var halls = new List<int>[n + 1];        for (int v = 0; v <= n; v++) halls[v] = new List<int>();        for (int i = 0; i < m; i++)        {            int a = int.Parse(data[2 + n + 2 * i]), b = int.Parse(data[3 + n + 2 * i]);            halls[a].Add(b);            halls[b].Add(a);        }         // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다        var arrive = new int[n + 1];        Array.Fill(arrive, -1);        arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다        var queue = new Queue<int>();        queue.Enqueue(1);        int reached = 1;        while (queue.Count > 0)        {            int u = queue.Dequeue();            int t = arrive[u] + 1; // 이웃 전시실에 닿는 시각            foreach (int v in halls[u])            {                // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다                if (arrive[v] == -1 && t <= close[v])                {                    arrive[v] = t;                    queue.Enqueue(v);                    reached++;                }            }        }         var sb = new StringBuilder();        sb.Append(reached).Append('\n');        for (int v = 1; v <= n; v++) sb.Append(arrive[v]).Append(v < n ? ' ' : '\n');        Console.Write(sb);    }}
C++main.cpp · 46 lines
#include <iostream>#include <queue>#include <vector>using namespace std; int main() {    ios::sync_with_stdio(false);    cin.tie(nullptr);    int n, m;    cin >> n >> m;    vector<int> close(n + 1); // close[v] = v번 전시실에 들어갈 수 있는 마지막 시각    for (int v = 1; v <= n; v++) cin >> close[v];     // 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)    vector<vector<int>> halls(n + 1);    for (int i = 0; i < m; i++) {        int a, b;        cin >> a >> b;        halls[a].push_back(b);        halls[b].push_back(a);    }     // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다    vector<int> arrive(n + 1, -1);    arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다    queue<int> q;    q.push(1);    int reached = 1;    while (!q.empty()) {        int u = q.front();        q.pop();        int t = arrive[u] + 1; // 이웃 전시실에 닿는 시각        for (int v : halls[u]) {            // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다            if (arrive[v] == -1 && t <= close[v]) {                arrive[v] = t;                q.push(v);                reached++;            }        }    }     cout << reached << '\n';    for (int v = 1; v <= n; v++) cout << arrive[v] << (v < n ? ' ' : '\n');    return 0;}
Cmain.c · 52 lines
#include <stdio.h>#include <stdlib.h> int main(void) {    int n, m;    if (scanf("%d %d", &n, &m) != 2) return 0;    int *close = malloc((n + 1) * sizeof(int)); // close[v] = v번 전시실에 들어갈 수 있는 마지막 시각    for (int v = 1; v <= n; v++) scanf("%d", &close[v]);     // 인접 목록을 배열 셋으로: head[v]에서 시작해 next[e]로 따라가며 to[e]를 본다    // 복도 하나가 양쪽으로 다니는 길 둘이 되므로 칸이 2m개 든다    int *head = malloc((n + 1) * sizeof(int));    int *next = malloc((2 * m + 1) * sizeof(int));    int *to = malloc((2 * m + 1) * sizeof(int));    for (int v = 0; v <= n; v++) head[v] = -1;    for (int i = 0; i < m; i++) {        int a, b;        scanf("%d %d", &a, &b);        to[2 * i] = b;        next[2 * i] = head[a];        head[a] = 2 * i;        to[2 * i + 1] = a;        next[2 * i + 1] = head[b];        head[b] = 2 * i + 1;    }     // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다    int *arrive = malloc((n + 1) * sizeof(int));    int *queue = malloc((n + 1) * sizeof(int)); // 전시실마다 한 번만 들어가니 n칸이면 된다    for (int v = 0; v <= n; v++) arrive[v] = -1;    arrive[1] = 0; // 1번에는 처음부터 있으니 close[1]은 보지 않는다    int qh = 0, qt = 0;    queue[qt++] = 1;    while (qh < qt) {        int u = queue[qh++];        int t = arrive[u] + 1; // 이웃 전시실에 닿는 시각        for (int e = head[u]; e != -1; e = next[e]) {            int v = to[e];            // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다            if (arrive[v] == -1 && t <= close[v]) {                arrive[v] = t;                queue[qt++] = v;            }        }    }     printf("%d\n", qt); // 큐에 한 번씩 들어간 전시실의 수    for (int v = 1; v <= n; v++) printf(v > 1 ? " %d" : "%d", arrive[v]);    printf("\n");    free(close); free(head); free(next); free(to); free(arrive); free(queue);    return 0;}
Craykonmain.cray · 44 lines
첫줄 = Console.ReadNumbers();n = 첫줄[0];m = 첫줄[1];// 목록은 10,000칸까지라 전시실 번호에서 1을 빼 0번부터 둔다// close[v] = v번 전시실에 들어갈 수 있는 마지막 시각close = Console.ReadNumbers(); // 인접 목록: halls[v] = v번 전시실과 복도로 이어진 전시실들(양쪽으로 다닌다)halls = [];for (v = 0; v < n; v++){    halls.Add([]);}for (i = 0; i < m; i++){    쌍 = Console.ReadNumbers();    halls[쌍[0] - 1].Add(쌍[1] - 1);    halls[쌍[1] - 1].Add(쌍[0] - 1);} // 너비 우선 탐색(BFS): 큐에서 꺼내는 차례가 곧 도착 시각이 이른 차례다arrive = NewList(n, -1);arrive[0] = 0; // 1번에는 처음부터 있으니 close는 보지 않는다queue = [0];// 앞에서 빼는 대신 머리 번호 head를 옮긴다head = 0;while (head < queue.Count){    u = queue[head];    head++;    t = arrive[u] + 1; // 이웃 전시실에 닿는 시각    foreach (v in halls[u])    {        // 처음 닿는 때가 가장 이른 때다. 그때 이미 잠겼으면 나중에 와도 잠겨 있다        if (arrive[v] == -1 && t <= close[v])        {            arrive[v] = t;            queue.Add(v);        }    }} Console.WriteLine(queue.Count); // 큐에 한 번씩 들어간 전시실의 수Console.WriteLine(arrive);