Under construction

Still being built. Things may change

Keys

Time limit2sMemory limit2048 MB

Summary
Given rooms holding keys and connectors that each need a specific key type, find the starting rooms that reach the fewest rooms.
Level

Medium7 of 10

Topics
Union-find, Graph, Hash map
Solved
No attempts yet

Problem

Timothy the architect has designed a new escape game. There are nn rooms numbered from 00 to n−1n - 1. Initially, each room contains exactly one key. Each key has a type, which is an integer between 00 and n−1n - 1, inclusive. The type of the key in room ii (0≤i≤n−10 \le i \le n - 1) is r[i]r[i]. Several rooms may hold keys of the same type, so the values r[i]r[i] are not necessarily distinct.

There are mm bidirectional connectors numbered from 00 to m−1m - 1. Connector jj (0≤j≤m−10 \le j \le m - 1) joins two different rooms u[j]u[j] and v[j]v[j]. A pair of rooms can be joined by more than one connector.

A single player collects keys and moves between rooms through the connectors. The player traverses connector jj when they move from u[j]u[j] to v[j]v[j] or from v[j]v[j] to u[j]u[j]. The player can traverse connector jj only after collecting a key of type c[j]c[j]. The player never discards a key.

The player is in some room xx and can perform two kinds of actions:

  • Collect the key in room xx, whose type is r[x]r[x], unless it has already been collected.
  • Traverse connector jj, where u[j]=xu[j] = x or v[j]=xv[j] = x, if the player has already collected a key of type c[j]c[j].

The player starts in room ss carrying no keys. Room tt is reachable from room ss if the player starting in room ss can perform some sequence of these actions and end up in room tt.

For each room ii (0≤i≤n−10 \le i \le n - 1), let p[i]p[i] be the number of rooms reachable from room ii. Timothy wants to know the set of indices ii that attain the minimum value of p[i]p[i] over 0≤i≤n−10 \le i \le n - 1.

Constraints

  • 2≤n≤300 0002 \le n \le 300\,000
  • 1≤m≤300 0001 \le m \le 300\,000
  • 0≤r[i]≤n−10 \le r[i] \le n - 1 for all 0≤i≤n−10 \le i \le n - 1
  • 0≤u[j],v[j]≤n−10 \le u[j], v[j] \le n - 1 and u[j]≠v[j]u[j] \ne v[j] for all 0≤j≤m−10 \le j \le m - 1
  • 0≤c[j]≤n−10 \le c[j] \le n - 1 for all 0≤j≤m−10 \le j \le m - 1

Examples1

  1. Example 1

    Input
    2 1
    0 1
    0 1 0
    
    Expected output
    1
    1