poj3017 dp+單調佇列
http://poj.org/problem?id=3017
Description
Given an integer sequence { an } of length N, you are to cut the sequence into several parts every one of which is a consecutive subsequence of the original sequence. Every part must satisfy that the sum of the integers in the part is not greater than a given integer M. You are to find a cutting that minimizes the sum of the maximum integer of each part.
Input
The first line of input contains two integer N (0 < N ≤ 100 000), M. The following line contains N integers describes the integer sequence. Every integer in the sequence is between 0 and 1 000 000 inclusively.
Output
Output one integer which is the minimum sum of the maximum integer of each part. If no such cuttings exist, output −1.
Sample Input
8 17 2 2 2 8 1 8 2 1
Sample Output
12
/**
poj3017 dp+單調佇列優化
題目大意:給定一個數列,把這個數列進行分割,每個小段的和不能超過m,求如何分配能使得每段的最大值的總和最小
解題思路:這道題猛地一看好像一個最大值最小化,其實並不是,這道題是求所有段最大值的和最小。我們用dp來寫
dp[i]=dp[j]+max(x[j+1],x[j+2],x[j+3]...x[i]).其中(x[j+1],x[j+2],x[j+3]...x[i])<=m.複雜度是O(n^2)
我們採取單調佇列的思想優化一下,O(n)的複雜度
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
typedef long long LL;
const int maxn=100005;
LL a[maxn],q[maxn],m,dp[maxn];
int n;
int main()
{
while(~scanf("%d%lld",&n,&m))
{
LL pos=0,last=0,cnt=0;
int front=1,rear=0,flag=0;
dp[0]=0;
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
if(a[i]>m)flag=1;
cnt+=a[i];
while(cnt>m)cnt-=a[++pos];
while(front<=rear&&a[q[rear]]<=a[i])
rear--;
q[++rear]=i;
while(front<=rear&&q[front]<=pos)
front++;
last=pos;
/// printf("(%d ",last+1);
dp[i]=0x3f3f3f3f3f3f3f3f;
for(int j=front;j<=rear;j++)
{
dp[i]=min(dp[i],dp[last]+a[q[j]]);
last=q[j];
}
/// printf("%d %d)\n",i,dp[i]);
}
if(flag)
printf("-1\n");
else
printf("%lld\n",dp[n]);
}
return 0;
}
相關文章
- HDU 3530 Subsequence (dp+單調佇列)佇列
- 單調佇列佇列
- 單調棧/單調佇列佇列
- 單調佇列雙端佇列佇列
- HDU3415 Max Sum of Max-K-sub-sequence (DP+單調佇列)佇列
- 單調棧 和 單調佇列佇列
- 單調棧和單調佇列佇列
- POJ 2823 單調佇列佇列
- hdu 3415 單調佇列佇列
- HDU 3530 單調佇列佇列
- hdu 3401 單調佇列+DP佇列
- hdu 4122 單調佇列佇列
- 單調佇列最佳化 DP佇列
- bzoj1597: [Usaco2008 Mar]土地購買(斜率優化+Dp+單調佇列)優化佇列
- POJ 3017 單調佇列dp佇列
- hdu4374單調佇列+dp佇列
- 佇列-單端佇列佇列
- noi.ac #289. 電梯(單調佇列)佇列
- 多重揹包問題的單調佇列優化佇列優化
- HDU3530 單調佇列的應用佇列
- C語言 簡單的佇列(陣列佇列)C語言佇列陣列
- hdu3415 單調佇列求區間最大和佇列
- hdu 4122Alice's mooncake shop(單調佇列)佇列
- [學習筆記] 單調佇列最佳化DP - DP筆記佇列
- POJ 2823Sliding Window(單調佇列水題)佇列
- RabbitMQ-簡單佇列MQ佇列
- 單向鏈式佇列佇列
- 棧,佇列,優先順序佇列簡單介面使用佇列
- POJ2823 Sliding Window (單調佇列的基本應用)佇列
- 多重揹包O(N*V)演算法詳解(使用單調佇列)演算法佇列
- laravel 佇列的簡單使用Laravel佇列
- 佇列_單向連結串列佇列
- 佇列、阻塞佇列佇列
- FZU 1894 單調佇列入門佇列
- 實現簡單延遲佇列和分散式延遲佇列佇列分散式
- BZOJ1044: [HAOI2008]木棍分割(dp 單調佇列)佇列
- 聯賽模擬測試18 A. 施工 單調佇列(棧)優化DP佇列優化
- BZOJ 3314 [Usaco2013 Nov]Crowded Cows:單調佇列佇列