您的位置:首页 > 其它

1033. To Fill or Not to Fill (25)

2013-11-14 13:29 381 查看
1033. To Fill or Not to Fill (25)

该问题是一个贪心算法问题,设满缸油可行驶的距离为s,当前加油站的位置为p1,那么需要找到在s距离内第一个油价比当前加油站油价便宜的点p2,如果s距离内p1油价最便宜,则加满;否则,保证p1位置油缸内的油缸号可以导致p2位置。

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class CA
{
public:
class cstation
{
public:
int point,addlen;
double price;
cstation(){point=0;addlen=0;price=0;}
bool operator < (const cstation& st)const
{
return point<st.point;
}
};
void run();
int c,d,avg,n;
vector<cstation> vst;
};

void CA::run()
{
cin>>c>>d>>avg>>n;
cstation st;
while(n-->0)
{
cin>>st.price>>st.point;
vst.push_back(st);
}
sort(vst.begin(),vst.end());
int taglen=c*avg;
int i,j,lastlevlen=0,lastpoint=0;
vector<int> curlist;
bool gotto=false;
for(i=0;i<vst.size();i++)
{
if(vst[i].point-lastpoint>lastlevlen) break;
lastlevlen-=vst[i].point-lastpoint;
int k=i;
for(j=i+1;j<vst.size();j++) //find first sheapest station
{
if(vst[j].point-vst[i].point<=taglen)
{
if(vst[j].price<vst[k].price) {k=j;break;}
}
else break;
}
if(k==i) vst[i].addlen=taglen-lastlevlen; //current station is sheapest ,fill tank
else vst[i].addlen=(vst[k].point-vst[i].point-lastlevlen)>0?(vst[k].point-vst[i].point-lastlevlen):0; //rearch the lastest cheaper station
lastpoint=vst[i].point;
lastlevlen+=vst[i].addlen;
if(vst[i].point+lastlevlen>=d)
{
vst[i].addlen-=vst[i].point+lastlevlen-d;
gotto=true;
break;
}
}
if(gotto)
{
double allprice=0;
for(i=0;i<vst.size();i++)
{
allprice+=vst[i].addlen*vst[i].price/avg;
}
printf("%.2f",allprice);
}
else
{
printf("The maximum travel distance = %.2f",double(lastpoint+lastlevlen));
}
}

int main()
{
//	freopen("test.in","r",stdin);
CA *a=new CA;
a->run();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  to Fill or Not Fi