Fxx and game HDU - 5945(单调队列优化dp)

思路:考虑反着dp,从dp[1]倒推dp[x]

因为dp[i]<=dp[j]  j<i  ,所以考虑用单调队列来优化。

除法不用考虑,考虑加法就行。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e6+7;
const int mod=1e9+7;
int x,k,t;
int dp[maxn];
deque<int> q;
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
        freopen("out.txt","w",stdout);
    #endif
    int T;
    cin>>T;
    while(T--)
    {
        scanf("%d%d%d",&x,&k,&t);
        if(t==0)
        {
            int an=0;
            while(x!=1)
            {
                x/=k;
                an++;
            }
            printf("%d\n",an);
            continue;
        }
        if(k==0)
        {
            printf("%d\n",(x-2)/t+1);
            continue;
        }
        dp[1]=0;
        while(q.size()) q.pop_back();
        q.push_back(1);
        for(int i=2;i<=x;i++)
        {
            dp[i]=inf;
            if(i%k==0) 
            {
                dp[i]=min(dp[i],dp[i/k]+1);
            }
            while(q.size()&&(i-t)>q.front())
            {
                q.pop_front();
            }
            if(q.size())
            {
                dp[i]=min(dp[i],dp[q.front()]+1);
            }
            while(q.size()&&dp[i]<dp[q.back()])
            {
                q.pop_back();
            }
            q.push_back(i);
        }
        printf("%d\n",dp[x]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40774175/article/details/82934849