To solve this problem, we need to consider the resource allocation for each program across all possible execution orders of the production steps, respecting the dependencies. The goal is to compute the minimal total number of machines required that can accommodate any permissible order, and allocate the machines accordingly.
Here is the step-by-step solution:
-
Parse Input: Read the dependency graph, the programs needed per step, and the machine requirements per program.
-
Compute Earliest Start Times (EST): Use a topological sort to compute the earliest possible start time for each step considering the dependencies. Assign levels (EST) to each step accordingly.
-
Determine Program Intervals:
- For each program, collect all steps that require it.
- Compute the earliest start time (
start_P) as the minimum EST of the steps needing the program.
- Compute the latest end time (
end_P) as the maximum EST of the steps needing the program, plus 1 (assuming each step takes 1 unit time).
- Build intervals
[start_P, end_P) representing when the program's machines will be occupied.
-
Create Events for Resource Allocation:
- For each program interval, create two events: a start event (at
start_P), where the program's machines are allocated, and an end event (at end_P), where the machines are released.
- Collect all events into a list and sort them by time.
-
Process Events and Allocate Machines:
- Initialize variables to track the total number of machines and the current allocation.
- For each event in chronological order:
- If it's a start event:
- Try to assign the program to the available machines (from the pool of released machines).
- If not enough machines are available, allocate new machines (incrementing the total machine count).
- Record the machines allocated to the program.
- If it's an end event:
- Release the machines back into the pool of available machines.
- Keep track of the maximum number of machines used at any point (this is the minimal total required).
-
Assign Machines to Steps:
- For each step:
- Sort the programs used in lexicographical order (dictionary order).
- Retrieve the starting machine index for each program from the previous allocation.
- Record the machine allocation per program for the step.
-
Output the Results:
- Print the minimal total number of machines required.
- For each step, print the step number, followed by each program used in that step and its starting machine index.
Below is the code that implements the solution:
import sys
import threading
def main():
import sys
import heapq
sys.setrecursionlimit(1 << 25)
graph_section = False
program_section = False
machine_section = False
graph_lines = []
program_lines = []
machine_lines = []
lines = sys.stdin.read().splitlines()
idx = 0
while idx < len(lines):
line = lines[idx]
if line == 'GRAPH':
graph_section = True
program_section = machine_section = False
idx += 1
continue
elif line == 'PROGRAM':
program_section = True
graph_section = machine_section = False
idx += 1
continue
elif line == 'MACHINE':
machine_section = True
graph_section = program_section = False
idx += 1
continue
else:
if graph_section:
graph_lines.append(line)
elif program_section:
program_lines.append(line)
elif machine_section:
machine_lines.append(line)
idx += 1
# Build the dependency graph
from collections import defaultdict, deque
steps = set()
graph = defaultdict(list)
in_degree = defaultdict(int)
for line in graph_lines:
if not line.strip():
continue
tokens = line.strip().split()
u, v = map(int, tokens)
graph[u].append(v)
in_degree[v] += 1
steps.update([u, v])
total_steps = steps
# Do topological sort to compute earliest start times (EST)
EST = {}
queue = deque()
for step in total_steps:
if in_degree.get(step, 0) == 0:
queue.append(step)
EST[step] = 0
while queue:
u = queue.popleft()
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
EST[v] = max(EST.get(v, 0), EST[u] + 1)
else:
EST[v] = max(EST.get(v, 0), EST[u] + 1)
# Parse programs per step
steps_programs = {}
programs_set = set()
for line in program_lines:
if not line.strip():
continue
tokens = line.strip().split()
step = int(tokens[0])
programs = tokens[1:]
steps_programs[step] = programs
programs_set.update(programs)
# Parse machines per program
program_machines_needed = {}
for line in machine_lines:
if not line.strip():
continue
tokens = line.strip().split()
program = tokens[0]
machines_needed = int(tokens[1])
program_machines_needed[program] = machines_needed
# For each program, compute start and end times
program_intervals = {}
program_steps = defaultdict(list) # Steps needing the program
for step, programs in steps_programs.items():
for program in programs:
program_steps[program].append(step)
for program in programs_set:
steps_needing_program = program_steps[program]
if not steps_needing_program:
continue
start_P = min(EST[step] for step in steps_needing_program)
end_P = max(EST[step] for step in steps_needing_program) + 1
program_intervals[program] = (start_P, end_P)
# Build events for allocation
events = []
for program in programs_set:
start_P, end_P = program_intervals[program]
machines_needed = program_machines_needed[program]
events.append((start_P, 0, program, machines_needed)) # 0 for start event
events.append((end_P, 1, program, machines_needed)) # 1 for end event
# Sort events by time, then by type (start before end)
events.sort(key=lambda x: (x[0], x[1]))
# Allocate machines
total_machines = 0
available_machines = []
machine_allocation = {} # program -> starting machine index
current_machines = 0
machine_index = 0
allocated_machines = {} # program -> list of machine indices
for time, event_type, program, machines_needed in events:
if event_type == 0: # Start event
# Try to reuse available machines
assigned_machines = []
while available_machines and len(assigned_machines) < machines_needed:
m = heapq.heappop(available_machines)
assigned_machines.append(m)
if len(assigned_machines) < machines_needed:
# Need to allocate new machines
needed = machines_needed - len(assigned_machines)
assigned_machines.extend(range(machine_index, machine_index + needed))
machine_index += needed
# Save the allocation
assigned_machines.sort()
allocated_machines[program] = assigned_machines
current_machines += machines_needed
total_machines = max(total_machines, current_machines)
else: # End event
# Release machines
assigned_machines = allocated_machines[program]
for m in assigned_machines:
heapq.heappush(available_machines, m)
current_machines -= machines_needed
# Now, for each step, output the allocation
# For the policy, need to output programs in lex order per step
output_steps = []
for step in sorted(steps_programs.keys()):
programs = steps_programs[step]
programs.sort()
allocations = []
for program in programs:
starting_machine = min(allocated_machines[program])
allocations.append(f"{program} {starting_machine}")
output_line = f"{step} {' '.join(allocations)}"
output_steps.append(output_line)
# Output the results
print(total_machines)
for line in output_steps:
print(line)
threading.Thread(target=main).start()