首页 > 代码库 > HDU 2105 三角形重心

HDU 2105 三角形重心

The Center of Gravity

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4159    Accepted Submission(s): 2403


Problem Description
Everyone know the story that how Newton discovered the Universal Gravitation. One day, Newton walked 
leisurely, suddenly, an apple hit his head. Then Newton discovered the Universal Gravitation.From then
on,people have sovled many problems by the the theory of the Universal Gravitation. What‘s more, wo also
have known every object has its Center of Gravity.
Now,you have been given the coordinates of three points of a triangle. Can you calculate the center 
of gravity of the triangle?
 


Input
The first line is an integer n,which is the number of test cases.
Then n lines follow. Each line has 6 numbers x1,y1,x2,y2,x3,y3,which are the coordinates of three points.
The input is terminated by n = 0.
 


Output
For each case, print the coordinate, accurate up to 1 decimal places.
 


Sample Input
2
1.0 2.0 3.0 4.0 5.0 2.0
1.0 1.0 4.0 1.0 1.0 5.0
0
 


Sample Output
3.0 2.7
2.0 2.3
 
 
题意:
给出三角形三个顶点的坐标,求这个三角形的重心。
 
思路:
三角形重心即三角形三边中线的交点,求出任意两边中线交点就行了。注意三角形中线可能没有斜率。
 
代码:
 1 #include <iostream> 2 #include <string> 3 #include <map> 4 #include <stdio.h> 5 #include <math.h> 6 using namespace std; 7 #define pi acos(-1) 8  9 10 main()11 {12      int t;13      double x1, y1, x2, y2, x3, y3, x4, y4, x5, y5;14      double k1, k2, b1, b2, x, y;15      while(scanf("%d",&t)==1&&t){16          while(t--){17          scanf("%lf %lf %lf %lf %lf %lf",&x1,&y1,&x2,&y2,&x3,&y3);18          x4=(x2+x3)/2;19          y4=(y2+y3)/2;20          x5=(x1+x3)/2;21          y5=(y1+y3)/2;22          if(x1==x4){23              k1=(y5-y2)/(x5-x2);24              b1=y2-k1*x2;25              x=x1;26              y=k1*x1+b1;27              printf("%.1lf %.1lf\n",x,y);continue;28          }29          if(x2==x5){30              k1=(y4-y1)/(x4-x1);31              b1=y1-k1*x1;32              x=x2;33              y=k1*x2+b1;34              printf("%.1lf %.1lf\n",x,y);continue;35          }36          k1=(y4-y1)/(x4-x1);37          k2=(y5-y2)/(x5-x2);38          b1=y1-x1*k1;39          b2=y2-x2*k2;40          x=(b1-b2)/(k2-k1);41          y=k1*x+b1;42          printf("%.1lf %.1lf\n",x,y);43        }44      }45      46 }