📄 fac5_10.java
字号:
//本程序取自王晓东编著“算法分析与设计”第 179 页,例
//园排列问题的回溯解法
//
class Cercles
{
static int n; //待排列圆的个数
static float min; //当前最优值
static float [] x; //当前圆排列圆心横坐标
static float [] r; //当前圆排列
public static float circlePerm(int nn,float [] rr)
{
n=nn;
min=100000;
x=new float[n+1];
r=rr;
backtrack(1);
return min;
}
private static void backtrack(int t)
{
if(t>n)compute();
else
{
for(int j=t;j<=n;j++)
{//
swap(r,t,j);
float centerx=center(t);
if(centerx+r[t]+r[1]<min)
{ x[t]=centerx;
backtrack(t+1);
}
swap(x,t,j);
}
}
}
static void swap(float[] a,int i1,int j1)
{
float temp;
temp=a[i1];
a[i1]=a[j1];
a[j1]=temp;
}
private static float center(int t)
{
float temp=0;
for(int j=1;j<t;j++)
{
float valuex=(float)(x[j]+ 2.0 * Math.sqrt(r[t]*r[j]));
if(valuex>temp)temp=valuex;
}
return temp;
}
private static void compute()
{
float low=0;
float high=0;
for(int i=1;i<=n;i++)
{
if(x[i]-r[i]<low)low=x[i]-r[i];
if(x[i]+r[i]>high)high=x[i]+r[i];
}
if(high-low<min)min=high-low;
}
}//
public class Fac5_10{
public static void main(String args[])
{
Cercles abc=new Cercles();
int n1=3;
float v1[]={0.0f,1.0f,1.0f,2.0f};
System.out.println("园排列问题的最优解 " + abc.circlePerm(n1,v1));
for(int k=1;k<=n1;k++)
System.out.print(" "+abc.x[k]);
System.out.println();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -