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
**********************************/
發佈了31 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章