Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

CODE:

import java.util.Arrays;
import java.util.Scanner;

public class Main {

static int minCost = Integer.MAX_VALUE;

// Function to find the minimum cost using Branch and Bound


static void branchAndBound(int[][] costMatrix, boolean[] assigned, int worker, int
currentCost) {
if (worker == costMatrix.length) {
// All workers are assigned, update the minimum cost
minCost = Math.min(minCost, currentCost);
return;
}

// Bound function: Calculate a lower bound for the current state


// (e.g., using a linear relaxation, heuristics, or any appropriate method)

for (int job = 0; job < costMatrix.length; job++) {


if (!assigned[job]) {
// Branch: Assign the worker 'worker' to job 'job'
assigned[job] = true;

// Recursively explore the next worker


branchAndBound(costMatrix, assigned, worker + 1, currentCost +
costMatrix[worker][job]);

// Unassign the worker 'worker' from job 'job' to backtrack


assigned[job] = false;
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of workers/jobs: ");


int n = scanner.nextInt();

int[][] costMatrix = new int[n][n];

System.out.println("Enter the cost matrix:");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
costMatrix[i][j] = scanner.nextInt();
}
}

boolean[] assigned = new boolean[n];


Arrays.fill(assigned, false);

branchAndBound(costMatrix, assigned, 0, 0);

System.out.println("Minimum cost: " + minCost);

scanner.close();
}
}

OUTPUT:

Enter the number of workers/jobs:


4
Enter the cost matrix:
9278
6437
5818
7694
Minimum cost: 13

You might also like