UVa:301 Transportation

一直都不太会写搜索题,这个题一开始写的非常烂,TLE了。主要是不知道该怎么处理人数这个题。我一开始的办法是递归每一站,然后每一站里再递归每次订票,每次的人数用结构体保存,这样一个状态就是一个结构体,在上站的时候加人数,下站的时候减人数。超时了。

后来学习了网上的办法,用数组表示人数,只用一个数组,数组的每个元素表示每站时候的人数,这样这个数组表示当前状态的人数,不像我那样浪费很多空间。。这样的话,只需要递归每次订票即可,不需要考虑每站的问题了。2^22次方,没剪枝,没超时。

 

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <stack>
#include <algorithm>
#define MAXN 100005
#define MOD 1000000007
#define INF 100000000
#define ll long long
//ios::sync_with_stdio(false)
using namespace std;
int n,m,q;
struct Order
{
    int st,ed,peo,cost;
    Order(int a=0,int b=0,int c=0,int d=0):st(a),ed(b),peo(c),cost(d) {}
    bool operator < (const Order p) const
    {
        if(st==p.st) return ed<p.ed;
        return st<p.st;
    }
};
vector<Order> vec;
int people[30],maxn;
bool Judge(int st,int ed,int peo)
{
    for(int i=st; i<ed; ++i)
        if(people[i]+peo>n) return false;
    return true;
}
void dfs(int cur,int sum)
{
    if(cur>=q||vec[cur].st>=m) maxn=max(maxn,sum);
    else
    {
        if(Judge(vec[cur].st,vec[cur].ed,vec[cur].peo))
        {
            for(int i=vec[cur].st; i<vec[cur].ed; ++i)
                people[i]+=vec[cur].peo;
            dfs(cur+1,sum+vec[cur].cost);
            for(int i=vec[cur].st; i<vec[cur].ed; ++i)
                people[i]-=vec[cur].peo;
        }
        dfs(cur+1,sum);
    }
}
int main()
{

    while(scanf("%d%d%d",&n,&m,&q))
    {
        if(!n&&!m&&!q) break;
        int x,y,z;
        vec.clear();
        for(int i=0; i<q; ++i)
        {
            scanf("%d%d%d",&x,&y,&z);
            vec.push_back(Order(x,y,z,(y-x)*z));
        }
        sort(vec.begin(),vec.end());
        memset(people,0,sizeof(people));
        maxn=0;
        dfs(0,0);
        printf("%d\n",maxn);
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值