Aufgabe 2

This commit is contained in:
Pia 2026-05-18 14:42:57 +02:00
parent d29755051d
commit ff07766822
5 changed files with 110 additions and 2 deletions

32
agt_übung2.py Normal file
View file

@ -0,0 +1,32 @@
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}")