POJ 1040 Transportation DFS

POJ 1040 Transportation DFS

题目描述:

  题目链接:“POJ 1040 Transportation”

题目大意:

  两地之间共有车站若干个,一次编号为 ,,, ;列车的最大载客量为 。每次列车开车前会受到条订票信息。订票信息包括,起点站,终点站,人数。票价等于起点与终点的车站数(包含终点,不包含起点)。因载客量限定,因此不能接受全部订单,同时若接受一条订单则必须全部接受。求最大利润并输出。

解题思路:

  将所有的订单按照距离始发站由近到远的顺序排序,如果两个相同,则按目标站距始发站的顺序排序。以车上的最大载客量作为判断标准,进行搜索。注意订单即使满足条件也可以不接受。故搜索的状态转移方程有两个

接受当前订单时: dfs(i+1,p+order[i].p,money+order[i].p(order[i].eorder[i].s));

不接受当前订单时: dfs(i+1,p,money);

复杂度分析:

时间复杂度 O(n2)
空间复杂度 O(n)

AC代码

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>

using namespace std;


const int maxm = 23;
const int maxn = 8;
int n,m,t;
int ans;
int down[maxn];

struct Order{
    int s,e,p;
    bool operator < (const Order &a) const{
        if(a.s == s) return e < a.e;
        return s < a.s;
    }
}order[maxm];


void dfs(int i, int p, int money){
    if(i == t){
        if(ans < money) ans = money;
        return;
    }
    if(i > 0)
        for (int j = order[i - 1].s + 1; j <= order[i].s; j++)
            p -= down[j];
    if(p + order[i].p <= n){
        down[order[i].e] += order[i].p;
        dfs(i + 1, p + order[i].p, money + order[i].p * (order[i].e - order[i].s));
        down[order[i].e] -= order[i].p;
    }
    dfs(i + 1, p, money);
}

int main(){
    while(scanf("%d %d %d",& n,& m,& t),t || n || m){
        for(int i = 0; i < t; i++)
            scanf("%d%d%d",& order[i].s,& order[i].e,& order[i].p);
            sort(order,order+t);
            ans = 0;
            memset(down,0,sizeof(down));
            dfs(0,0,0);
            printf("%d\n",ans);
        }
    return 0;
}
/********************************
10 3 4
0 2 1
1 3 5
1 2 7
2 3 10
10 5 4
3 5 10
2 4 9
0 2 5
2 5 8
0 0 0
**********************************/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值