-
Notifications
You must be signed in to change notification settings - Fork 1
/
圆排列问题.cpp
70 lines (70 loc) · 1.57 KB
/
圆排列问题.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
using namespace std;
const int inf = 0x3f3f3f3f;
int n=3;
double x[110];//每个圆的横坐标
double r[110];//每个圆的半径
double minnr[110];//最短圆序列的半径
double minn=inf;//存放最短圆排列长度
double calCenter(int k){//计算圆心坐标
double temp=0;
for(int i=1;i<k;i++){
double c=x[i]+2.0*sqrt(r[i]*r[k]);
temp=max(c,temp);
}
return temp;
}
void calLength(){//计算圆排列的总长度
double low=inf,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<minn){
minn=high-low;
for(int i=1;i<=n;i++){
minnr[i]=r[i];
}
}
}
void backtrack(int k){ //查找圆排列
if(k>n){//结束排列,计算排列长度
calLength();
return ;
}
for(int i=k;i<=n;i++){
swap(r[k],r[i]);
double center=calCenter(k);//获取圆当前的横坐标
if(center+r[1]+r[k]<minn){//剪枝操作
x[k]=center;
backtrack(k+1);//向下继续搜索
}
swap(r[k],r[i]);//回溯
}
}
int main() {
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
scanf("%d",&n);
printf("给出%d圆,每个圆的半径分别为:",n);
for(int i=1;i<=n;i++){
scanf("%lf",&r[i]);
printf("%f ",r[i]);
}
puts("");
backtrack(1);
printf("最小圆排列长度为:%f\n",minn);
printf("最短圆序列:\n");
for(int i=1;i<=n;i++){//输出最短圆序列
printf("%f ",minnr[i]);
}
puts("");
return 0;
}