比较有意思的一个题目
问题:车上有2列椅子,同一列中相邻椅子的距离为1,两列之间的距离为2,椅子上有一些乘客,现在上来上个人,如何使他们之间的距离和最短?
解决:如果两列得某一列中有连续3个空位,则是最短距离为4。否则,按照2为坐标把空位存储到vector<pair>中,(x,y) 第一列为(0,i),第二列为(2,i),然后按照y排序,如果y相同,按照x排序。这样对排序好的数组依次取3个计算距离,取最小值。
程序:
#include <vector>
#include <map>
#include <algorithm>
#include <string>
#include <complex>
#include <iostream>
using namespace std;
struct cmp
{
bool operator()(pair<int,int>p1,pair<int,int>p2)
{
return p1.second==p2.second?(p1.first<p2.first):p1.second<p2.second;
}
};
class BusSeating
{
private:
double deal(pair<int,int>p1,pair<int,int>p2,pair<int,int>p3)
{
double d1 = sqrt((double)(p1.first-p2.first)*(p1.first-p2.first)+(p1.second-p2.second)*(p1.second-p2.second));
double d2 = sqrt((double)(p1.first-p3.first)*(p1.first-p3.first)+(p1.second-p3.second)*(p1.second-p3.second));
double d3 = sqrt((double)(p3.first-p2.first)*(p3.first-p2.first)+(p3.second-p2.second)*(p3.second-p2.second));
return d1+d2+d3;
}
public:
double getArrangement(string l, string r)
{
string s = "---";
if(l.find(s)!=string::npos||r.find(s)!=string::npos)
return 4.0;
vector<pair<int,int> >px;
int i = 0;
while((i=l.find('-',i))!=string::npos)
px.push_back(make_pair(0,i++));
i =0;
while((i=r.find('-',i))!=string::npos)
px.push_back(make_pair(2,i++));
sort(px.begin(),px.end(),cmp());
double min = 100000;
for(int i = 0; i< px.size()-2;i++)
{
double tmp = deal(px[i],px[i+1],px[i+2]);
cout<<tmp<<endl;
if(min > tmp+1e-9)
min = tmp;
}
return min;
}
};