Minimum Cost Demand Fulfillment Solution
Problem Statement
You are given a directed graph with `N` nodes and `M` edges. Each edge `(u, v)` has an associated `cost_per_unit` and a `capacity`. You are also given a `source_node` and a list of `target_demands`. Each `target_demand` is a pair `[node_id, required_amount]`, indicating that `required_amount` units of a resource must be delivered to `node_id`. The `source_node` has an unlimited supply of resources. Your task is to find the minimum total cost to satisfy all `target_demands` while respecting the `capacity` of each edge. The cost for sending `F` units of resource through an edge `(u, v)` with `cost_per_unit` is `F * cost_per_unit`. If it is impossible to satisfy all demands due to capacity limitations or unreachable target nodes, return -1.
Examples
Constraints
- `1 <= N <= 100` (Number of nodes)
- `0 <= M <= N * (N - 1)` (Number of edges)
- `0 <= cost_per_unit <= 1000` for each edge
- `0 <= capacity <= 100` for each edge
- `0 <= required_amount <= 50` for each demand
- `0 <= source_node, node_id < N`
- Target nodes in `target_demands` are distinct.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
N, M = map(int, sys.stdin.readline().strip().split())
edges = []
for _ in range(M):
u, v, cost_per_unit, capacity = map(int, sys.stdin.readline().strip().split())
edges.append([u, v, cost_per_unit, capacity])
source_node = int(sys.stdin.readline().strip())
target_demands = []
for line in sys.stdin:
node_id, required_amount = map(int, line.strip().split())
target_demands.append([node_id, required_amount])
graph = [[] for _ in range(N + 1)]
for u, v, cost_per_unit, capacity in edges:
graph[u].append([v, cost_per_unit, capacity])
def min_cost_demand_fulfillment(N, M, edges, source_node, target_demands):
min_cost = [float("inf")] * (N + 1)
min_cost[source_node] = 0
for _ in range(N):
for u, v, cost_per_unit, capacity in edges:
if min_cost[u] != float("inf") and min_cost[u] + cost_per_unit < min_cost[v]:
min_cost[v] = min_cost[u] + cost_per_unit
total_cost = 0
for node_id, required_amount in target_demands:
if min_cost[node_id] == float("inf"):
return -1
total_cost += min_cost[node_id] * required_amount
return total_cost
result = min_cost_demand_fulfillment(N, M, edges, source_node, target_demands)
print(result)