poj 3257(哈希+二维dp)

来源:互联网 发布:wifi万能钥匙for mac 编辑:程序博客网 时间:2024/06/04 00:48

题意:要连出一个从1-L的过山车线,给出n段可选的建设方案。每段都有起始位置,终止位置,代价,和乐趣程度。要实现1-L的长度中,相邻两端要首尾相连,总建设代价控制在B之内,问最多能获得多少乐趣程度。


解题思路:这里有两个限制条件,L和B,最开始的思维可能是dp[i][j][k]表示前i段,修的长度为j,花费为k的最大价值。但根据数据量,这样肯定会超时。这里同样有一个条件要仔细挖掘,相邻两端要首尾相连,所以对应长度为L,肯定要有一个段它的其实位置等于L,这样我们就可以把每一段的首地址用哈希存起来,到时候枚举到L就直接从哈希里面拿出来,这样就会少了枚举所有段的一层循环。dp[i][j]表示修的长度为i,花费为j的最大价值


#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 10005;struct Node{int start,end,len,cost,fun;}roller[maxn];struct HashNode{int id,next;}HNode[maxn];int L,N,B,dp[1005][1005]; //dp[i][j]表示修建的长度为i,花费为j的最大值int h[maxn],cnt;bool cmp(Node a,Node b){if(a.start == b.start) return a.end < b.end;return a.start < b.start;}void add(int len,int id){HNode[cnt].id = id, HNode[cnt].next = h[len];h[len] = cnt++;}int main(){while(scanf("%d%d%d",&L,&N,&B)!=EOF){memset(h,-1,sizeof(h));memset(dp,-1,sizeof(dp));for(int i = 1; i <= N; i++){scanf("%d%d%d%d",&roller[i].start,&roller[i].len,&roller[i].fun,&roller[i].cost);roller[i].end = roller[i].start + roller[i].len;}dp[0][0] = 0;for(int i = 1; i <= N; i++)add(roller[i].start,i);//加入哈希节点for(int i = 0; i <= L; i++)for(int j = 0; j <= B; j++){if(dp[i][j] == -1) continue;int t = h[i];while(t != -1){if(roller[HNode[t].id].cost + j <= B)dp[roller[HNode[t].id].end][j + roller[HNode[t].id].cost] = max(dp[roller[HNode[t].id].end][j+roller[HNode[t].id].cost],dp[i][j]+roller[HNode[t].id].fun);t = HNode[t].next;}}int ans = -1;for(int i = 0; i <= B; i++)ans = max(ans,dp[L][i]);printf("%d\n",ans);}return 0;}


0 0