程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 2014遼寧ACM省賽 Distance

2014遼寧ACM省賽 Distance

編輯:C++入門知識

問題 E: Distance

時間限制: 1 Sec 內存限制: 128 MB
提交: 48 解決: 12
[提交][狀態][論壇]

題目描述

There is a battle field. It is a square with the side length 100 miles, and unfortunately we have two comrades who get hurt still in the battle field. They are in different positions. You have to save them. Now I give you the positions of them, and you should choose a straight way and drive a car to get them. Of course you should cross the battle field, since it is dangerous, you want to leave it as quickly as you can!

輸入

There are many test cases. Each test case contains four floating number, indicating the two comrades' positions (x1,y1), (x2,y2).

Proceed to the end of file.

輸出

you should output the mileage which you drive in the battle field. The result should be accurate up to 2 decimals.

樣例輸入

1.0 2.0 3.0 4.0 15.0 23.0 46.5 7.0

樣例輸出

140.01 67.61

提示

The battle field is a square local at (0,0),(0,100),(100,0),(100,100).


一道幾何題,求出 邊界上的兩點 (x0,y0),(xn,yn)就可以了,不過有一些特殊情況得討論,比如分母為0。

#include
#include
#include
#include
#include
using namespace std;
double distance(double x0,double y0,double xn,double yn)
{
    return sqrt((x0-xn)*(x0-xn)+(y0-yn)*(y0-yn));
}
double f1(double x,double x1,double y1,double x2,double y2)
{
    return (y1-y2)/(x1-x2)*(x-x2)+y2;
}
double f2(double y,double x1,double y1,double x2,double y2)
{
    return (x1-x2)/(y1-y2)*(y-y2)+x2;
}
int main()
{
    double x1,y1;
    double x2,y2;
    while(cin>>x1>>y1>>x2>>y2)
    {
        double x0,y0,xn,yn;
        if(y1==y2||x1==x2)
        {
            printf("100.00\n");
            continue;
        }
        x0=0;
        xn=100;
        y0=f1(x0,x1,y1,x2,y2);
        yn=f1(xn,x1,y1,x2,y2);
      //  cout<100&&y0>=0&&y0<=100)
        {
            yn=100;
            xn=f2(yn,x1,y1,x2,y2);
        }
        else if(yn>100&&y0<0)
        {
            yn=100;
            xn=f2(yn,x1,y1,x2,y2);
            y0=0;
            x0=f2(y0,x1,y1,x2,y2);
        }
        else if(y0<0&&yn>=0&&yn<=100)
        {
            y0=0;
            x0=f2(y0,x1,y1,x2,y2);
        }
        else if(y0>100&&yn>=0&&yn<=100)
        {
            y0=100;
            x0=f2(y0,x1,y1,x2,y2);
        }
        else if(y0>100&&yn<0)
        {
            y0=100;
            x0=f2(y0,x1,y1,x2,y2);
            yn=0;
            xn=f2(yn,x1,y1,x2,y2);
        }
        else if(y0>=0&&y0<=100&&yn<0)
        {
            yn=0;
            xn=f2(yn,x1,y1,x2,y2);
        }
        printf("%.2lf\n",distance(x0,y0,xn,yn));
    }
    return 0;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved