一直都不太会写搜索题,这个题一开始写的非常烂,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;
}