agt_exercise/agt_übung2.py
2026-05-18 14:42:57 +02:00

32 lines
No EOL
902 B
Python

from pulp import *
def min_vertexcover(nodes, edges):
#Problemdefinition
prob = LpProblem("Kleinste Knotenüberdeckung", LpMinimize)
#Binäre Variablen
x = {v: LpVariable(f"x_{v}", cat=LpBinary) for v in nodes}
#Zielfunktion
prob += lpSum(x[v] for v in nodes)
#Nebenbedingung
for u,v in edges:
prob += x[u] + x[v] >=1, f"Kante_{u}_{v}"
#Lösen mit gurobi
prob.solve(GUROBI())
#Ergebnis
status = LpStatus[prob.status]
vertex_cover = [v for v in nodes if value(x[v]) == 1]
return status, vertex_cover, value(prob.objective)
nodes_test = ['A', 'B', 'C', 'D', 'E']
edges_test = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'D'), ('D', 'E')]
status, cover, size = min_vertexcover(nodes_test, edges_test)
print(f"Status: {status}")
print(f"Minimale Knotenüberdeckung: {cover}")
print(f"Größe der Überdeckung: {size}")