Advertisement
Eternoseeker

Ad-Ass6-BranchnBound

Nov 24th, 2023
602
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | Source Code | 0 0
  1. import numpy as np
  2.  
  3. def club_assignment_bnb(cost_matrix):
  4.     n = len(cost_matrix)
  5.     if n == 0 or len(cost_matrix[0]) != n:
  6.         raise ValueError("Invalid cost matrix")
  7.  
  8.     def bound(node, level):
  9.         bound_val = 0
  10.         assigned_students = set()
  11.         assigned_clubs = set()
  12.        
  13.         for i in range(level):
  14.             assigned_students.add(node[i][0])
  15.             assigned_clubs.add(node[i][1])
  16.             bound_val += cost_matrix[node[i][0]][node[i][1]]
  17.  
  18.         for i in range(level, n):
  19.             min_cost = float('inf')
  20.             for j in range(n):
  21.                 if j not in assigned_clubs:
  22.                     min_cost = min(min_cost, cost_matrix[i][j])
  23.             bound_val += min_cost
  24.  
  25.         return bound_val
  26.  
  27.     def branch_and_bound(node, level, min_cost, min_assignment):
  28.         nonlocal best_cost, best_assignment
  29.         if level == n:
  30.             current_cost = sum(cost_matrix[node[i][0]][node[i][1]] for i in range(n))
  31.             if current_cost < best_cost:
  32.                 best_cost = current_cost
  33.                 best_assignment = node.copy()
  34.         else:
  35.             for i in range(n):
  36.                 if i not in set(node[j][0] for j in range(level)):
  37.                     new_node = node.copy()
  38.                     new_node.append((i, level))
  39.                     new_bound = bound(new_node, level + 1)
  40.                     if new_bound < best_cost:
  41.                         branch_and_bound(new_node, level + 1, min_cost, min_assignment)
  42.  
  43.     best_cost = float('inf')
  44.     best_assignment = []
  45.     branch_and_bound([], 0, best_cost, best_assignment)
  46.  
  47.     return best_cost, [(student, club) for (student, club) in best_assignment]
  48.  
  49. # Get user input for the cost matrix
  50. n = int(input("Enter the number of students and clubs (N): "))
  51. print("Enter the cost matrix:")
  52. cost_matrix = []
  53. for i in range(n):
  54.     row = list(map(int, input().split()))
  55.     if len(row) != n:
  56.         print("Invalid input. Please enter a square matrix.")
  57.         exit(1)
  58.     cost_matrix.append(row)
  59.  
  60. min_cost, assignment = club_assignment_bnb(cost_matrix)
  61. print(f"Minimum Cost: {min_cost}")
  62. print("Assignment:")
  63. for student, club in assignment:
  64.     print(f"Student {student} to Club {club}")
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement