D - ウイルス検査と感染端末 / Virus Testing and Infected Terminals 解説 by admin
DeepSeek V3Overview
This problem asks us to determine the virus infection status of terminals in a network, finding the minimum number of infected terminals that is consistent with the given test results.
Analysis
Since the number of terminals \(N\) is at most 16, which is small, it is possible to exhaustively search all combinations of infection states for all terminals (\(2^N\) combinations). For each combination, we check whether it is consistent with all M test results, and among the consistent ones, we select the one with the minimum number of infected terminals. Since the size allows for exhaustive search with a straightforward approach, this runs sufficiently fast without any particular optimization.
Algorithm
We use bitmask enumeration. We represent the infection state of terminals as an N-bit bitmask and try all states from 0 to \(2^N-1\). For each state, we verify consistency with the test results using the following procedure:
- Count the number of set bits in the bitmask (this is the number of infected terminals); if it is greater than the current minimum, skip it.
- For each test:
- Check whether at least one of the terminals being tested is infected (i.e., the corresponding bit is set in the bitmask).
- If the test result is “infection detected” (R_j=1) but no infected terminal is found among the tested terminals, or if the result is “no infection” (R_j=0) but an infected terminal is found, then this state is invalid.
- Among all states that pass every test, output the minimum number of infected terminals.
Complexity
- Time complexity: \(O(M \cdot N \cdot 2^N)\)
- Space complexity: \(O(M \cdot N)\)
Implementation Notes
Each bit of the bitmask corresponds to a terminal number (terminal i corresponds to bit position i-1).
For consistency checking with test results, the set of terminals tested in each test is stored in advance and checked efficiently using bitwise operations.
States with a number of infected terminals greater than the current minimum are pruned early, providing a slight efficiency improvement.
Source Code
def main():
import sys
data = sys.stdin.read().splitlines()
if not data:
print(0)
return
first_line = data[0].split()
N = int(first_line[0])
M = int(first_line[1])
scans = []
for i in range(1, M+1):
parts = data[i].split()
K_j = int(parts[0])
S_list = list(map(int, parts[1:1+K_j]))
R_j = int(parts[-1])
scans.append((S_list, R_j))
min_infected = float('inf')
total_possible = 1 << N
for mask in range(total_possible):
valid = True
count = bin(mask).count('1')
if count >= min_infected:
continue
for S_list, R_j in scans:
found = False
for node in S_list:
idx = node - 1
if mask & (1 << idx):
found = True
break
if (R_j == 1 and not found) or (R_j == 0 and found):
valid = False
break
if valid:
if count < min_infected:
min_infected = count
print(min_infected)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
投稿日時:
最終更新: