[topCoder-每日一二题]--[5]

比较有意思的一个题目

问题:车上有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;
  
 }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值