ichi - 单调栈

题目大意:
你要建n座塔,每座塔有一个高度h,每一趟你可以带k块砖头,随意选择一个位置开始。每一步你可以向左或者向右或者向上爬(如果没有转头就必须摆一个砖头),问最少多少趟。
题解:
一开始考虑从下往上,gg。
考虑从上往下,每次选最高的一个,将其填到和其两侧一样高,这时可能会多出一些剩余,记录一下,并且合并两或三列。
这个过程可以用单调栈优化。

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define Rep(i,v) rep(i,0,(int)v.size()-1)
#define lint long long
#define ull unsigned lint
#define db long double
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define gc getchar()
#define debug(x) cerr<<#x<<"="<<x
#define sp <<" "
#define ln <<endl
using namespace std;
typedef pair<int,int> pii;
typedef set<int>::iterator sit;
inline int inn()
{
    int x,ch;while((ch=gc)<'0'||ch>'9');
    x=ch^'0';while((ch=gc)>='0'&&ch<='9')
        x=(x<<1)+(x<<3)+(ch^'0');return x;
}
const int N=100010;
struct node{
    int h,w;lint res;
    node(int _h=0,int _w=0,lint _r=0) { h=_h,w=_w,res=_r; }
}s[N];
inline lint q(lint c,int k) { return (c+k-1)/k; }
int main()
{
    int n=inn(),k=inn(),t=0;lint ans=0;
    rep(i,1,n+1)
    {
        int h=(i<=n?inn():0),w=1;lint res=0;
        for(;t&&s[t].h>=h;t--)
        {
            lint c=(s[t].h-max(s[t-1].h,h))*(lint)s[t].w,r=s[t].res;
            if(c<=r) r-=c;else c-=r,ans+=q(c,k),r=q(c,k)*k-c;
            if(s[t-1].h>=h) s[t-1].w+=s[t].w,s[t-1].res+=r;
            else w+=s[t].w,res+=r;
        }
        s[++t]=node(h,w,res);
    }
    return !printf("%lld\n",ans);
}

猜你喜欢

转载自blog.csdn.net/Mys_C_K/article/details/84893167