动态规划排线算法问题java语言实现
问题描述:
在一块电路板的上、下2端分别有n个接线柱。根据电路设计,要求用导线(i,π(i))将上端接线柱与下端接线柱相连,确定将哪些连线安排在第一层上,使得该层上有尽可能多的连线。该问题要求确定导线集Nets={(i,π(i)),1≤i≤n}的最大不相交子集
java语言
//动态规划排线算法
public class DynamicAlorithm {
//求最大值
public static int MAX(int a,int b) {
int max=a>b?a:b;
return max;
}
public static void Circut_Alorithm(int[] a, int [][]set, int n) {
int i, j;
for (i = 0; i < n; i++)
{
set[i][0] = 0;
set[0][i] = 0;
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
//考虑两种情况
if (a[i] != j)
set[i][j] = MAX(set[i - 1][j], set[i][j - 1]);
else
set[i][j] = set[i - 1][j - 1] + 1;
}
}
}
//回调递归计算最大不相交连线的电路排线并输出回路内容
public static void Print_Circut(int i, int j, int set[][]){
if (i == 0)
return;
if (set[i][j] == set[i - 1][j])
Print_Circut(i - 1, j, set);
else if (set[i][j] == set[i][j - 1])
Print_Circut(i, j - 1, set);
else
{
Print_Circut(i - 1, j - 1, set);
System.out.println(" <"+i+"--"+j+"> ");
}
}
public static void main(String[]args) {
//初始化
int a[] = { 0, 6, 3, 5, 2, 9, 4, 1, 10, 7, 8 };
int set[][]=new int[11][11];
Circut_Alorithm(a, set, 10);
System.out.println("最大不相交连线的个数:"+set[10][10]);
System.out.println("最大不相交连线的电路排线如下:");
Print_Circut(10, 10, set);
}
}
结果截图: