无限的路
Problem Description
甜甜从小就喜欢画图画,最近他买了一支智能画笔,由于刚刚接触,所以甜甜只会用它来画直线,于是他就在平面直角坐标系中画出如下的图形:
甜甜的好朋友蜜蜜发现上面的图还是有点规则的,于是他问甜甜:在你画的图中,我给你两个点,请你算一算连接两点的折线长度(即沿折线走的路线长度)吧。
Input
第一个数是正整数N(≤100)。代表数据的组数。
每组数据由四个非负整数组成x1,y1,x2,y2;所有的数都不会大于100。
Output
对于每组数据,输出两点(x1,y1),(x2,y2)之间的折线距离。注意输出结果精确到小数点后3位。
Sample Input
5
0 0 0 1
0 0 1 0
2 3 3 1
99 99 9 9
5 5 5 5
Sample Output
1.000
2.414
10.646
54985.047
0.000
注意用x+y只和去解决问题
解法1:
# include <iostream>
# include <cmath>
# include <cstdio>
using namespace std;
int main(){
double x1,x2,y1,y2,k,t;
int n;
double sum ;
while(cin>>n){
while(n--){
cin>>x1>>y1>>x2>>y2;
sum = 0;
if(x1+y1==x2+y2){
sum = sqrt(pow(x1-x2,2)+pow(y1-y2,2));
printf("%.3lf\n",sum);
continue;
}else if(x1+y1>x2+y2) {
t = x1,x1 = x2,x2 = t;
t = y1,y1 = y2,y2 = t;
}
while(1){
if(x1+y1==x2+y2){
break;
}
k = x1 + y1;
sum+=sqrt((k-x1)*(k-x1)+y1*y1)+sqrt(k*k+(k+1)*(k+1));
x1 = 0,y1 = k + 1;
}
sum+=sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
printf("%.3lf\n",sum);
}
}
return 0;
}
解法2:
# include <iostream>
# include <cstdio>
# include <cmath>
using namespace std;
int main(){
double x1,x2,y1,y2,sum,t;
int n;
while(cin>>n){
while(n--){
cin>>x1>>y1>>x2>>y2;
if(x1+y1>x2+y2){
t=x1,x1=x2,x2=t;
t=y1,y1=y2,y2=t;
}
sum = 0;
sum=(y1-y2)*sqrt(2);//去除多余的线段,在for循环内多算出的
for(double i=x1+y1+1;i<=x2+y2;i++){
sum+=i*sqrt(2.0) + sqrt(i*i+(i-1)*(i-1));
}
printf("%.3lf\n",sum);
}
}
return 0;
}