以文本方式查看主题

-  计算机科学论坛  (http://bbs.xml.org.cn/index.asp)
--  『 算法理论与分析 』  (http://bbs.xml.org.cn/list.asp?boardid=60)
----  求解"加油问题"  (http://bbs.xml.org.cn/dispbbs.asp?boardid=60&rootid=&id=39285)


--  作者:北纬26度
--  发布时间:10/24/2006 10:15:00 PM

--  求解"加油问题"
假定你要在I-80公路上驱车从旧金山到纽约市.你的汽车装有C加仑汽油,可以行驶m英里.I-80公路上n个加油站机器所售汽油的价格的一览表,设di为第i个加油站距离旧金山的距离,ci是在第i个加油站加油的开销.假设对于任意两个加油站i和j,它们之间的距离di-dj为的m倍数.你从加油站1出发时,油箱为空.你的最终目的地为加油站n.在你到达目的地n时,油箱油料至少为0.试设计一多项式时间动态规划算法,输出穿过这段公路所需的最小汽油量.并根据n和C,分析你所设计的算法的运算时间.
  需注意的是,当油箱中的汽油量小于0时,汽车不能行驶;当你决定在某站加油时,也不必加满油箱.
--  作者:vingo555
--  发布时间:10/31/2006 12:25:00 PM

--  
没有调试过。

#define N (10)  //set the total station
#define OIL_PER_KM (1)
#define INIT_OIL (5)
#define MAX_CONTAINER (100)
struct station
{
 float dist;
 float price;
};


float curr;
struct station st[N];

void init_station()
{
 //int i;
 curr = INIT_OIL;

 //initilize the station information
 st[0].dist = 0;
 st[N].price = MAX_LONG;
 //otherinformation should be filled according to the actually.
}
// 0 -- for increment always
// 1 == exist decrement,but the low state's prices is higher the the from state
// -1 -- the last station
int check_state(int from,int to,int &ret)
{
 int i ;
 int retValue = 0;
 if(from == to) {
  return -1;
 }
 for(i = from ; i < to ; i ++) {
  if(st[i].price > st[i + 1].price) {
   if(st[i + 1].price > st[from].price) {
    retValue = 1;   
   } else {
    retValue = 2;    
   }
   ret = i + 1;
   break;
  }
 }

 return retValue;
}
float get_oli(int from,int to)
{
 int i;
 float total = 0.0;
 if(from == to) {
  return total;
 }
 for(i =from ; i <= to ; i ++) {
  total += st[i].dist;
 }

 return (total * OIL_PER_KM);
}
float try_search()
{
 int i ,j, retValue,newIndex;
 float tmp, cost = 0;
  do{
  curr -= st[i].dist * OIL_PER_KM;

  if(st[i].price >= st[i + 1].price) {   
   tmp = get_oli(i,i+1);
   cost += (tmp - curr) * st[i].price;
   curr = tmp;
   i ++;
  } else {
   for(j = i + 1; j < N - 1; j ++) {
    tmp = MAX_CONTAINER;
    tmp -= st[j].dist * OIL_PER_KM;

    if(tmp < 0) {
     break;
    }
   }
   //this is the station we can reach,if the
   j --;
   retValue = check_state(i,j,newIndex);
   if(retValue == 0) {    
    cost += (MAX_CONTAINER - curr) * st[i].price;
    curr = MAX_CONTAINER ;
    i ++;
   } else if(retValue == 1) {
    tmp = get_oli(i,newIndex);
    cost += (tmp - curr) * st[i].price;
    curr = tmp;
    i = newIndex;
   } else {
    tmp = ( st[i +1].dist * OIL_PER_KM - curr);
    if(tmp > 0 ) {
     cost += tmp * st[i].price;
    }
    i ++;
   }
  }
 }while(i < N -1);
  return cost;
}


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
26.367ms