POJ_1040 感悟
来源:互联网 发布:v380监控软件官网 编辑:程序博客网 时间:2024/06/11 12:04
花了两天的时间做了1040这道题。
刚开始自己写了一个算法,题目给的数据和自己编制的验证数据都对,但是就是不能通过,感觉还是自己的验证能力不够。
后来在网上看了一个剪枝法的DFS,感觉这个算法非常不错。
首先将订单排好序(为了更好的剪枝),然后从小到大的顺序加费用和并保存在各个订单中。计算时,从大订单开始,循环每个订单。
剪枝:如果这个订单的费用和+已有的总费用<最大值,则以后的小订单都不遍历,即剪枝。
这个算法值得学习
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
class Order
{
public:
int beginStation;
int endStation;
int people;
int fee;
int earning;
};
static int _count = 0;
int _max=0;
int station[30];
Order *orders;
int capacity,lastStation,ordersNum;
void DFS(int begin , int earning );
int UpGreat(const void*a ,const void*b){return (((Order*)b)->fee -((Order*)a)->fee);}
int main(int argc , char* argv[])
{
while (cin>>capacity>>lastStation>>ordersNum , capacity!=0 ||lastStation!=0 ||ordersNum!=0)
{
int sum = 0 ;
int beginStation;
int endStation;
int people;
int i;
orders = new Order[ordersNum];
for ( i=0 ; i<ordersNum; i++)
{
cin>>beginStation>>endStation>>people;
orders[i].beginStation = beginStation;
orders[i].endStation = endStation;
orders[i].people = people;
orders[i].fee = ( endStation - beginStation ) *people;
}
qsort((Order*)orders,ordersNum,sizeof(Order),UpGreat);
for ( i=ordersNum-1 ; i >=0 ; --i)
{
sum += orders[i].fee;
orders[i].earning = sum;
}
for (i=0 ; i<=lastStation ; i++)
{
station[i] =0;
}
DFS(0,0);
cout<<_max<<endl;
}
delete []orders;
return EXIT_SUCCESS;
}
void DFS(int odth , int earning )
{
if ( earning > _max)
{
_max = earning;
}
for (int i = odth; i<ordersNum ; i++)
{
if (orders[i].earning + earning <= _max)
{
return ;
}
int begin = 0;
for( begin=orders[i].beginStation ; begin<orders[i].endStation ; begin++)
{
station[begin] += orders[i].people;
if (station[begin] > capacity)
{
break;
}
}
if (begin == orders[i].endStation)
{
DFS(i+1,earning+orders[i].fee);
--begin;
}
for (int j=begin ; j>=orders[i].beginStation ; j--)
{
station[j] -= orders[odth].people;
}
}
}
- POJ_1040 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟!
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- 感悟
- quartus10.1的licence问题
- PlayOnLinux 让你更方便地在linux上玩windows游戏
- Monkey学习
- 本地html文件的打开方法
- Android插件
- POJ_1040 感悟
- Hello C++
- Error error PRJ0002 : 从“cl.exe”返回的结果有误 in VS 2008
- 关于UIActionSheet(上拉菜单)的使用
- 测试amd cpu对intel sse指令集的支持情况
- 2011年2月《当安全厂商遭遇被开源》
- actionSheet(上拉菜单)的实现
- 我的网盘管理了这么多天,也没有增加多少空间
- jquery与javascript中的两个页面加载事件 window.onload 与 $(document).ready(function(){})区别