?
? ? ? ??dp[k]是非遞增的,然后對于同樣的轉移代價,我們只需要找到i最小的dp[i]及可。
?所以可以用單調隊列維護一個遞減的序列,存儲轉移代價,即一段中的最大值。對于每個轉移代價下的dp[i]+a[j],把它壓入set中。每次找到最小的值來更新dp[k]。
?
? ? ? ? 維護隊列,set,有比較麻煩的邊界條件,要好好處理。
?
#include <iostream> #include <cstdio> #include <cstring> #include <set> using namespace std; const int maxn=1e5+9; typedef long long ll; multiset <ll> d; ll n,m; int a[maxn]; struct { int id,data; }que[maxn]; long long dp[maxn]; int main() { d.insert((ll)1<<50); scanf("%lld %lld",&n,&m); for(int i=1;i<=n;i++) scanf("%d",&a[i]); int st=1,ed=0,low=1; long long sum=0; for(int i=1;i<=n;i++) { if(a[i]>m) { printf("-1\n"); return 0; } sum+=a[i]; while(sum>m) sum-=a[low++]; while(ed>=st&&a[i]>=que[ed].data) { if(ed>st) d.erase(d.find(dp[que[ed-1].id]+a[que[ed].id])); ed--; } if(ed>=st) d.insert(dp[que[ed].id]+a[i]); que[++ed].data=a[i]; que[ed].id=i; while(que[st].id<low&&ed>=st) { if(st<ed) d.erase(d.find(dp[que[st].id]+a[que[st+1].id])); st++; } long long tmp=min(*d.begin(),dp[low-1]+que[st].data); dp[i]=tmp; } printf("%lld",dp[n]); return 0; }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
