题目:

终于到周末啦!小易走在市区的街道上准备找朋友聚会,突然服务器发来警报,小易需要立即回公司修复这个紧急bug。假设市区是一个无限大的区域,每条街道假设坐标是(X,Y),小易当前在(0,0)街道,办公室在(gx,gy)街道上。小易周围有多个出租车打车点,小易赶去办公室有两种选择,一种就是走路去公司,另外一种就是走到一个出租车打车点,然后从打车点的位置坐出租车去公司。每次移动到相邻的街道(横向或者纵向)走路将会花费walkTime时间,打车将花费taxiTime时间。小易需要尽快赶到公司去,现在小易想知道他最快需要花费多少时间去公司。
输入描述:

输入数据包括五行:

第一行为周围出租车打车点的个数n(1 ≤ n ≤ 50)

第二行为每个出租车打车点的横坐标tX[i] (-10000 ≤ tX[i] ≤ 10000)

第三行为每个出租车打车点的纵坐标tY[i] (-10000 ≤ tY[i] ≤ 10000)

第四行为办公室坐标gx,gy(-10000 ≤ gx,gy ≤ 10000),以空格分隔

第五行为走路时间walkTime(1 ≤ walkTime ≤ 1000)和taxiTime(1 ≤ taxiTime ≤ 1000),以空格分隔

输出描述:

输出一个整数表示,小易最快能赶到办公室的时间

输入例子:

2
-2 -2
0 -2
-4 -2
15 3

输出例子:

42

分析:

因为是坐标网格,所以总路径的长度是固定值,所以,只需找出距离出发点最近的出租车打车点即可(还要排除掉直接走路去公司的情况)。

算法代码:

int getDistance(Point & point1, Point & point2)
{
    return abs(point1.getX() - point2.getX()) + abs(point1.getY() - point2.getY());
}

int goToCompany(Point * taxi, int n, Point & home ,Point & company, int walkTime, int taxiTime)
{
    vector<int> time(n+1);
    
    for (int i = 0; i < n; ++i) {
        time[i] = walkTime * getDistance(taxi[i], home) + taxiTime * getDistance(taxi[i], company);
    }
    time[n] = walkTime * getDistance(home, company);
    
    auto minTimeIter = min_element(time.begin(), time.end());
    
    return *minTimeIter;
}

测试代码:

//
//  main.cpp
//  goToCompany
//
//  Created by Jiajie Zhuo on 2017/4/6.
//  Copyright © 2017年 Jiajie Zhuo. All rights reserved.
//

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

class Point
{
private:
    int _X;
    int _Y;
public:
    Point() : _X(0), _Y(0) {}
    ~Point() {}
    void setX(int x) {this->_X = x;}
    void setY(int y) {this->_Y = y;}
    int getX() {return _X;}
    int getY() {return _Y;}
};

int getDistance(Point & point1, Point & point2);
int goToCompany(Point * taxi, int n, Point & home ,Point & company, int walkTime, int taxiTime);

int main(int argc, const char * argv[]) {
    int n;
    cout << "Please enter the number of taxis: ";
    cin >> n;
    
    Point * taxi = new Point[n];
    
    int tX;
    cout << "Please input tX: ";
    for (int i = 0; i < n; ++i) {
        cin >> tX;
        taxi[i].setX(tX);
    }
    
    int tY;
    cout << "Please input tY: ";
    for (int i = 0; i < n; ++i) {
        cin >> tY;
        taxi[i].setY(tY);
    }
    
    Point home;
    
    Point company;
    int gX, gY;
    cout << "Please input gX and gY: ";
    cin >> gX >> gY;
    company.setX(gX);
    company.setY(gY);
    
    int walkTime, taxiTime;
    cout << "Please input walkTime and taxiTime: ";
    cin >> walkTime >> taxiTime;
    
    int minTime = goToCompany(taxi, n, home, company, walkTime, taxiTime);
    
    cout << "The minimum time of going to company is " << minTime << endl;
    
    delete [] taxi;
    
    return 0;
}

总结:

发现问题的关键点:总路径的长度是固定值,所以问题转化为了寻找(出租车)距离的最小值。