參考:http://blog.csdn.net/dreamvyps/article/details/6069844
菜鳥,一直對DFS很困惑。。。。
測試數據:http://poj.org/showmessage?message_id=17837
不要忘了處理訂單數爲0的情況
//Problem: 1040
//Memory: 224K Time: 438MS
//Language: C++ Result: Accepted
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const unsigned MaxOrder = 22;
const unsigned MaxStop = 7;
typedef struct _ORDER
{
int from;
int to;
int passengerCnt;
int value;//該order可以得到的價值
}Order;
vector<Order> order;
int stop[MaxStop];
int capacity,station,ordernum;
int maxV;
inline bool cmp(const Order &a, const Order &b)//按照每個order的value進行降序排序
{
return a.value>b.value;
}
void Dfs(int s, int curMaxV)
{
if(curMaxV>maxV)
maxV = curMaxV;
if(s>=order.size())
return;
int i, j;
for(i=s; i<order.size(); ++i)
{
for(j=order[i].from; j<order[i].to; ++j)
{
stop[j] += order[i].passengerCnt;
if(stop[j]>capacity)
break;
}
if(j==order[i].to)//還有空餘座位
{
Dfs(i+1,curMaxV+order[i].value);
--j;
}
//回溯
for(int k=j; k>=order[i].from; --k)
stop[k] -= order[i].passengerCnt;
}
}
int main()
{
Order tmp;
int i;
cin>>capacity>>station>>ordernum;
while(capacity!=0)
{
if(ordernum==0)//處理order爲0的情況
{
cout<<0<<endl;
}
else
{
memset(stop,0,sizeof(stop));
for(i=0; i<ordernum; ++i)
{
cin>>tmp.from>>tmp.to>>tmp.passengerCnt;
if(tmp.passengerCnt<=capacity)//如果單張訂單的乘客數大於容量則直接忽略該訂單
{
tmp.value = (tmp.to-tmp.from)*tmp.passengerCnt;
order.push_back(tmp);
}
}
sort(order.begin(),order.end(),cmp);//將所有的order按照其提供的價值進行降序排序
maxV = 0;
Dfs(0,0);
cout<<maxV<<endl;
order.clear();
}
cin>>capacity>>station>>ordernum;
}
return 0;
}