fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstdio>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. int n,st[100100],head=1,tail,pos[100100],active[100100];
  8. long long s[100100],f[100100],m;
  9. priority_queue < pair<long long,int> > q;
  10.  
  11. int main()
  12. {
  13. // freopen("difmax.inp" , "r" , stdin);
  14. // freopen("difmax.ans" , "w" , stdout);
  15. int x;
  16. cin >> n >> m;
  17. for (int i=1,j=0;i<=n;i++)
  18. {
  19. scanf("%d",&x);
  20. if (x>m)
  21. {
  22. cout << -1 << endl;
  23. return 0;
  24. }
  25.  
  26. while (tail>=head && x>=st[tail]) active[pos[tail--]]=0;
  27. st[++tail]=x; pos[tail]=i;
  28.  
  29. s[i]=s[i-1]+x;
  30. while (s[i]-s[j]>m) j++;
  31. while (head<=tail && pos[head]<=j) active[pos[head++]]=0;
  32. active[pos[head]]=0;
  33.  
  34. f[i]=f[j]+st[head];
  35. while (!q.empty())
  36. {
  37. pair <long long,int> u=q.top();
  38. if (!active[u.second]) q.pop();
  39. else
  40. {
  41. f[i]=min(f[i],-u.first);
  42. break;
  43. }
  44. }
  45. if (tail>head)
  46. {
  47. f[i]=min(f[i],f[pos[tail-1]]+st[tail]);
  48. q.push(make_pair(-f[pos[tail-1]]-st[tail],i));
  49. }
  50. else q.push(make_pair(0LL,i));
  51. active[i]=1;
  52. }
  53. cout << f[n] << endl;
  54. }
  55.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
0