时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
给定平面上N个点P1, P2, … PN,将他们按顺序连起来,形成一条折线。
请你求出这条折线的中点坐标。
输入
第一行包含一个整数N。 (2 <= N <= 100)
以下N行每行包含两个整数Xi, Yi代表Pi的坐标。(0 <= Xi, Yi <= 10000)
输出
输出折线段的中点坐标。坐标保留一位小数。
样例输入
3
0 0
30 30
40 20
样例输出
20.0 20.0
Solution1:从折线的两个端点出发,以相同的步长向前推进,注意处理同时到达折线端点的情况。
QAQ: 代码一直出错。。。先贴出来。。。以后有时间再修改吧
//代码Wrong
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
const int N = 105;
//const double EPS = 0.1;
typedef struct{
int x,y;
double dis;
}P;
P p[N];
int n;
double step = 10000*sqrt(2);
void Read(){
scanf("%d",&n);
scanf("%d%d",&p[1].x,&p[1].y);
for(int i=2;i<=n;i++){
scanf("%d%d",&p[i].x,&p[i].y);
p[i-1].dis = sqrt((p[i].x-p[i-1].x)*(p[i].x-p[i-1].x)+(p[i].y-p[i-1].y)*(p[i].y-p[i-1].y));
if(p[i-1].dis < step) step = p[i-1].dis; //得到最短折线段长
}
step = step*0.2; //步长小于最短折线长的一半
}
void Solve(){
int i = 1;
int j = n-1;
double dis1 = 0.0;
double dis2 = 0.0;
while(true){
if(dis1+step > p[i].dis){
dis1 = step-(p[i].dis-dis1);
i ++;
}
else dis1 += step;
if(dis2+step > p[j].dis){
dis2 = step-(p[j].dis-dis2);
j --;
}
else dis2 += step;
if(i == j){ //同一个折线端点
dis1 += (p[i].dis-dis1-dis2)/2;
break;
}
if(i+1 == j) //同一条线段
break;
}
// printf("%lf,%lf\n",dis1,dis2);
printf("%.1lf %.1lf\n",p[i].x+(p[i+1].x-p[i].x)*dis1/p[i].dis,p[i].y+(p[i+1].y-p[i].y)*dis1/p[i].dis);
}
int main(){
Read();
Solve();
return 0;
}
Solution2: 对各线段长度累加,然后二分查找
和的一半对应的位置即可
//AC代码
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
const int N = 105;
typedef struct{
int x,y;
double dis;
}P;
P p[N]; //p[i].dis表示前i条折线累计长度
int n;
double Dis(int i){
return sqrt((p[i].x-p[i-1].x)*(p[i].x-p[i-1].x)+
(p[i].y-p[i-1].y)*(p[i].y-p[i-1].y));
}
void Read(){
scanf("%d",&n);
scanf("%d%d",&p[0].x,&p[0].y);
p[0].dis = 0.0; //init
for(int i=1;i<n;i++){
scanf("%d%d",&p[i].x,&p[i].y);
p[i].dis = Dis(i)+p[i-1].dis;
}
}
int BS(int low, int high, double d){
int mid;
while(low < high){
mid = (low+high)/2;;
if(p[mid].dis < d) low = mid+1;
else high = mid;
}
return high;
}
void Cal(){
double d = p[n-1].dis/2;
int pos = BS(1,n-1,d);//二分
double len = p[pos].dis-p[pos-1].dis;//第pos条折线长度
d -= p[pos-1].dis;//中点距离第pos条折线起点长度
printf("%.1lf %.1lf\n",p[pos-1].x+(p[pos].x-p[pos-1].x)*(d/len)
,p[pos-1].y+(p[pos].y-p[pos-1].y)*(d/len));
}
int main(){
Read();
Cal();
return 0;
}
注: 如果各线段的dis数组单独定义,那么二分查找可以直接调用库函数lower_bound
,具体为:
int pos = lower_bound(dis+1,dis+n,dis[n-1]/2)-dis
此处参照:(http://hihocoder.com/contest/offers48/solution/1273059)