清华 最小花费 动态规划

题目描述:
    在某条线路上有N个火车站,有三种距离的路程,L1,L2,L3,对应的价格为C1,C2,C3.其对应关系如下:
    距离s           票价
    0<S<=L1         C1
    L1<S<=L2        C2
    L2<S<=L3        C3
    输入保证0<L1<L2<L3<10^9,0<C1<C2<C3<10^9。
    每两个站之间的距离不超过L3。
    当乘客要移动的两个站的距离大于L3的时候,可以选择从中间一个站下车,然后买票再上车,所以乘客整个过程中至少会买两张票。
    现在给你一个 L1,L2,L3,C1,C2,C3。然后是A B的值,其分别为乘客旅程的起始站和终点站。
    然后输入N,N为该线路上的总的火车站数目,然后输入N-1个整数,分别代表从该线路上的第一个站,到第2个站,第3个站,……,第N个站的距离。
    根据输入,输出乘客从A到B站的最小花费。

输入:
    以如下格式输入数据:
    L1  L2  L3  C1  C2  C3
    A  B
    N
    a[2]
    a[3]
    ……
    a[N]

输出:
    可能有多组测试数据,对于每一组数据,
    根据输入,输出乘客从A到B站的最小花费。

样例输入:

    1 2 3 1 2 3
    1 2
    2
    2

样例输出:

    2
---------------------
思路:线性规划

出现问题:1.在计算花费时候,如果距离为0,那么结果为0

                   2.给出的是第1个站到2,第1个到3的距离,看清题目

                   3.在循环中cost=min(cost,todp(l+i+1,r)+dtoc(as));的前提是if(as<=L3&&l+i+1<=r),所以这个if具有一定有。否则。。就花费了两个小时 哭。。。
                   

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
using namespace std;
const int Max=1000;
const int INF=900000000;
int dp[Max][Max];
bool vist[Max][Max];
int N,A,B;
int L1,L2,L3,C1,C2,C3;
int dis[Max];
int main()
{
	int dtoc(int s);
	int todp(int l,int r);
    cin>>L1>>L2>>L3>>C1>>C2>>C3;
    cin>>A>>B;
    if(A>B) swap(A,B);
    cin>>N;
    memset(vist,0,sizeof(vist));
    int pre=0;
    int iinput;
    for(int i=1;i<N;i++)
    {
    	cin>>iinput;
    	dis[i]=iinput-pre;
    	pre=iinput;
    	dp[i][i]=0;
		vist[i][i]=true;
    	dp[i][i+1]=dtoc(dis[i]);
    	vist[i][i+1]=true;
    }
     dp[N][N]=0;
	 vist[N][N]=true;
    int cost=todp(A,B);
    cout<<cost<<endl;
    
}
int dtoc(int s);
int todp(int l,int r)
{
	if(vist[l][r]) return dp[l][r];
	vist[l][r]=true;
	int cost=INF;
	int as=0;
	for(int i=0;as<=L3&&l+i+1<=r;i++)
	{
		as=as+dis[l+i];
		if(as<=L3&&l+i+1<=r)
		cost=min(cost,todp(l+i+1,r)+dtoc(as));
	}
	return dp[l][r]=cost;
}
int dtoc(int s)
{
	int cost=C3;
	if(s==0)
	cost=0;
	else if(s>0&&s<=L1)
	cost=C1;
	else if(s>L1&&s<=L2)
	cost=C2;
	else if(s>L2&&s<=L3)
	{
	  cost=C3;	
	}
	
	return cost;
}

           

猜你喜欢

转载自blog.csdn.net/qiang_____0712/article/details/85110726