Official

E - 照明スイッチ / Light Switch Editorial by admin Editorial for printing

GLM 5.2 (High)

Overview

This problem can be modeled as a shortest path problem on a graph, where the states of the \(N\) lights are represented as \(2^N\) vertices. The goal is to find the minimum cost to transition from the initial state (all lights off) to the target state (all lights on) without passing through any specified “danger patterns”.

Observations

Since \(N\) is at most 18, which is small, there are only \(2^{18} = 262144\) possible states for the lights. Each state can be represented as an integer (bitmask) from \(0\) to \(2^N-1\).

Operating switch panel \(j\) means transitioning from the current state \(v\) to state \(v \oplus m\) (where \(m\) is the bitmask of flipped lights for switch panel \(j\), and \(\oplus\) denotes bitwise XOR) with a cost of \(C_j\).

The problem condition “the state immediately after an operation must not match any danger pattern” translates to the constraint “we must not pass through vertices corresponding to danger patterns” on the graph. Therefore, the problem reduces to finding the shortest path from vertex \(0\) (all lights off) to vertex \(2^N-1\) (all lights on) while avoiding the danger patterns.

Note that pressing the same switch twice returns the lights to their original state. Thus, if there are multiple switches with the same flip pattern, we can keep only the one with the minimum cost to reduce the number of transitions and improve computational efficiency.

Algorithm

We search for the shortest path using Dijkstra’s algorithm.

  1. Preprocessing Switches: Read the flip mask \(m\) and cost \(c\) for each switch from the input. If there are multiple switches with the same \(m\), record only the minimum \(c\) (switches with all bits set to \(0\) can be ignored since they do not change the state).
  2. Recording Danger Patterns: Record the danger patterns in an array danger. Set flags so that danger[v] = True.
  3. Running Dijkstra’s Algorithm:
    • Start from the initial state v = 0 with an initial cost of d = 0.
    • Use a priority queue to manage the reachable vertices and their tentative minimum costs.
    • From the current vertex \(v\), calculate the next state \(nv = v \oplus m\) for each switch \((m, c)\).
    • If \(nv\) is a danger pattern, skip the transition.
    • If the tentative cost to \(nv\) can be updated, add it to the queue.
    • The cost when we first reach the target state \(2^N-1\) is the minimum cost. If the target state is unreachable, output -1.

Complexity

  • Time Complexity: \(O(2^N \cdot M \log (2^N)) = O(2^N \cdot M \cdot N)\). Since the number of states is \(V = 2^N \le 262144\) and the number of unique switches is \(S \le M \le 20\), and we try at most \(S\) transitions from each state, this will easily run within the time limit.
  • Space Complexity: \(O(2^N)\). We allocate space of size \(2^N\) for the distance array dist and the danger pattern array danger.

Key Implementation Points

  • Since the input size can be large, we use sys.stdin.buffer.read().split() to read the entire input at once for fast I/O.

  • For switches with the same flip pattern, we store only the one with the minimum cost in a dict (dictionary) to reduce the computational complexity.

  • State transitions are calculated as v ^ m. If the destination state corresponds to danger[nv], we immediately continue to prune the path search.

    Source Code

import sys
import heapq

def main():
    data = sys.stdin.buffer.read().split()
    if not data:
        return
    N = int(data[0])
    M = int(data[1])
    K = int(data[2])
    idx = 3
    
    switch_map = {}
    for _ in range(M):
        m = 0
        for i in range(N):
            if data[idx] == b'1':
                m |= 1 << i
            idx += 1
        c = int(data[idx])
        idx += 1
        if m != 0:
            if m not in switch_map or c < switch_map[m]:
                switch_map[m] = c
    switches = list(switch_map.items())
            
    V = 1 << N
    danger = bytearray(V)
    for _ in range(K):
        f = 0
        for i in range(N):
            if data[idx] == b'1':
                f |= 1 << i
            idx += 1
        danger[f] = 1
        
    start = 0
    goal = V - 1
    
    INF = 10**18
    dist = [INF] * V
    dist[start] = 0
    pq = [(0, start)]
    
    while pq:
        d, v = heapq.heappop(pq)
        if v == goal:
            print(d)
            return
        if d > dist[v]:
            continue
        for m, c in switches:
            nv = v ^ m
            if danger[nv]:
                continue
            nd = d + c
            if nd < dist[nv]:
                dist[nv] = nd
                heapq.heappush(pq, (nd, nv))
                
    print(-1)

if __name__ == "__main__":
    main()

This editorial was generated by or-glm5.2-high.

posted:
last update: