poj 3017 Cut the Sequence(dp单调队列优化)
2015-01-29 10:47
447 查看
题意:
给出n个连续的数字,现在可以将这些数分成很多段(不限制多少段),每段的最大值作为这段的价值,问如何使得总价值小。
题解:
看了题目一点思路都没有,果断看了神犇的博客,算法特别巧妙,感觉把队列优化用的非常娴熟。
思路是这样的,对于每个位置i我定义这样的状态dp[i]表示到i位置位置价值的最小值。
那么dp方程 dp[i] = min{ dp[j] , max{ a[j+1],a[j+2],.....,a[i] } }
那么我们要将后面的用队列优化下,定义k表示i最左能取到的下标的前一个(sum[i,k]<=m且sum[i,k-1]>m)
那么我们要取的j其实就是队列中存的下标,从队列头到尾进行dp
给出n个连续的数字,现在可以将这些数分成很多段(不限制多少段),每段的最大值作为这段的价值,问如何使得总价值小。
题解:
看了题目一点思路都没有,果断看了神犇的博客,算法特别巧妙,感觉把队列优化用的非常娴熟。
思路是这样的,对于每个位置i我定义这样的状态dp[i]表示到i位置位置价值的最小值。
那么dp方程 dp[i] = min{ dp[j] , max{ a[j+1],a[j+2],.....,a[i] } }
那么我们要将后面的用队列优化下,定义k表示i最左能取到的下标的前一个(sum[i,k]<=m且sum[i,k-1]>m)
那么我们要取的j其实就是队列中存的下标,从队列头到尾进行dp
#include<iostream> #include<math.h> #include<stdio.h> #include<algorithm> #include<string.h> #include<vector> #include<map> using namespace std; typedef __int64 lld; #define oo 0x3f3f3f3f #define OO 0x3f3f3f3f3f3f3f3f #define maxn 100000+5 lld dp[maxn]; lld a[maxn]; int q[maxn]; int main() { int n,f=0,k=0; int head=0,tail=-1; lld m,cnt=0; scanf("%d %I64d",&n,&m); for(int i=1;i<=n;i++) { scanf("%I64d",&a[i]); if(a[i]>m) f=1; cnt+=a[i]; //k表示i最小的不超过m的和的最小下标的前一个 while(cnt>m) k++,cnt-=a[k]; while(head<=tail&&a[q[tail]]<=a[i]) tail--; q[++tail]=i; while(head<=tail&&q[head]<=k) head++; dp[i]=OO; int temp=k; for(int j=head;j<=tail;j++) { if(dp[i]>dp[temp]+a[q[j]]) dp[i]=dp[temp]+a[q[j]]; temp=q[j]; } } if(f) dp =-1; printf("%I64d\n",dp ); return 0; }
相关文章推荐
- poj 3017 Cut the Sequence dp+单调队列优化
- POJ-3017 Cut the Sequence(DP单调队列优化 + 平衡树)
- POJ 3017 Cut the Sequence 【DP+单调队列优化+平衡树】
- POJ - 3017 Cut the Sequence : 单调队列优化dp
- Poj 3017 Cut the Sequence (DP,单调队列优化,数据结构优化)
- POJ 3017 Cut the Sequence (单调队列优化DP)
- POJ 3017 Cut the Sequence(DP + 单调队列优化 + 平衡树)
- POJ Cut the Sequence 单调队列优化DP入门题
- poj 3017 Cut the Sequence(单调队列优化 )
- POJ_3017 Cut the Sequence 单调队列+dp+BST
- poj 3017 Cut the Sequence(DP+单调队列)
- POJ 3017 Cut the Sequence(dp+单调队列)
- poj 3017 Cut the Sequence(DP+单调队列+set)
- POJ - 3017 Cut the Sequence(单调队列+dp)
- POJ 3017|Cut the Sequence|动态规划|单调队列
- POJ 3017 Cut the Sequence 单调队列
- Cut the Sequence (单调队列优化DP)
- POJ-3017 Cut the Sequence DP+单调队列+堆
- Cut the Sequence,Sequence Partitioning,POJ3017,POJ3245,用单调队列优化的DP
- poj3017 Cut the Sequence 单调队列优化dp 好题!