题目地址:Sicily 1012. Stacking Cylinders
思路:
最低层如果有n个圆,则一共会有n层,其中最高一层有1个。用n个数组记录n层圆的坐标,一开始输入底层的坐标,排序之后再不断利用下一层的坐标算出当前一层的坐标,知道最高层就行。对于每一个圆心坐标,可以用支撑它的下面两个圆心坐标通过几何计算方法算出。注意输出的格式。
代码:
1 #include<iostream> 2 #include<iomanip> 3 #include<cmath> 4 #include<algorithm> 5 using namespace std; 6 7 struct Point{ 8 double x,y; 9 }; 10 11 void get_a_point_from_two_below(Point &p,const Point &p1,const Point &p2); 12 bool cmp(const Point &p1,const Point &p2){ 13 return p1.x<p2.x; 14 } 15 16 int main(){ 17 int number_of_cylinders; 18 while(cin>>number_of_cylinders&&number_of_cylinders!=0){ 19 Point *level[number_of_cylinders]; 20 for(int i=0;i<number_of_cylinders;i++) //create room for each level of cylinders. 21 level[i]=new Point[number_of_cylinders-i]; 22 for(int i=0;i<number_of_cylinders;i++){ //get data of the bottom level 23 cin>>level[0][i].x; 24 level[0][i].y=1; 25 } 26 sort(level[0],level[0]+number_of_cylinders,cmp); 27 for(int i=1;i<number_of_cylinders;i++){ 28 for(int j=0;j<number_of_cylinders-i;j++){ 29 get_a_point_from_two_below(level[i][j],level[i-1][j], 30 level[i-1][j+1]); 31 } 32 } 33 cout.setf(ios::fixed); 34 cout<<setprecision(4)<<level[number_of_cylinders-1][0].x<<' ' 35 <<level[number_of_cylinders-1][0].y<<endl; 36 for(int i=0;i<number_of_cylinders;i++) 37 delete level[i]; 38 } 39 return 0; 40 } 41 void get_a_point_from_two_below(Point &p,const Point &p1,const Point &p2){ 42 double side=sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2)); 43 p.x=p1.x+2*cos(acos(side/4)+atan((p2.y-p1.y)/(p2.x-p1.x))); 44 p.y=p1.y+2*sin(acos(side/4)+atan((p2.y-p1.y)/(p2.x-p1.x))); 45 }