问题描述:
对给定的n个任务与n个人之间的成本矩阵完成成本最低的任务分配策略。
input:
1
4
2 1 6,1 2 2,1 3 7,1 4 8,1 1 9,2 2 4,2 3 3,2 4 7,3 1 5,3 2 8,3 3 1,3 4 8,4 1 7,4 2 6,4 3 9,4 4 4
output:
2 1 3 4
代码:
import java.util.*;
public class Main {
public static void allSort(String[] str,int pos,ArrayList<String[]> allsort_str){
if(pos == str.length-1){
allsort_str.add(str);
}else{
for(int i=pos;i<str.length;i ++){
String temp = str[pos];//the char in the pos
str[pos] = str[i];
str[i] = temp;
allSort(str.clone(),pos+1,allsort_str);
str[i] = str[pos];
str[pos] = temp;
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int exampleCount = Integer.parseInt(input.nextLine()); //测试用例数字个数
while(exampleCount > 0){
int size = Integer.parseInt(input.nextLine());//matrix size
String[] data = input.nextLine().split(",");
Integer[][] matrix = new Integer[size][size];//task matrix
for(int i=0;i<size*size;i ++){ //fill the matrix
String[] part_data = data[i].split(" ");
int m = Integer.parseInt(part_data[0]);
int n = Integer.parseInt(part_data[1]);
matrix[m-1][n-1] = Integer.parseInt(part_data[2]);
}
int num = 1;
for(int i=size;i>1;i --){
num = num*i;
}
String[] str = new String[size];
for(int i=0;i<size;i ++){
str[i] = String.valueOf(i);
}
ArrayList<String[]> list = new ArrayList<>();
allSort(str,0,list);
ArrayList result = new ArrayList<>();//store the result
int mincost = Integer.MAX_VALUE;
//get the least cost
for(int i=0;i<num;i ++){
String[] temp = list.get(i);
int current = 0;
for(int j=0;j<size;j ++){
current += matrix[j][Integer.parseInt(temp[j])];
}
if(mincost > current){
mincost = current;
}
}
int resultnum = 0;
//get the least cost sort
for(int i=0;i<num;i ++){
String[] temp = list.get(i);
int current = 0;
for(int j=0;j<size;j ++){
current += matrix[j][Integer.parseInt(temp[j])];
}
if(mincost == current){
resultnum ++;
StringBuffer sb = new StringBuffer();
for(int k=0;k<size;k ++){
sb.append(temp[k]);
}
String s = sb.toString();
result.add(s);
}
}
Collections.sort(result);
for(int i=resultnum-1;i>=0;i --){
String output = (String) result.get(i);
for(int j=0;j<size;j ++){
if(j == size-1){
if(i == 0){
System.out.print(Integer.parseInt(String.valueOf(output.charAt(j)))+1);
}else{
System.out.print(Integer.parseInt(String.valueOf(output.charAt(j)))+1+",");
}
}else{
System.out.print(Integer.parseInt(String.valueOf(output.charAt(j)))+1+" ");
}
}
}
System.out.println();
exampleCount --;
}
}
}