HDU 5945 Fxx and game (DP+单调队列优化)

Fxx and game

Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 1339    Accepted Submission(s): 358


Problem Description
Young theoretical computer scientist Fxx designed a game for his students.

In each game, you will get three integers X,k,t .In each step, you can only do one of the following moves:

1.X=Xi(0<=i<=t) .

2. if k|X,X=X/k .

Now Fxx wants you to tell him the minimum steps to make X become 1.
 

Input
In the first line, there is an integer T(1T20)ru indicating the number of test cases.

As for the following T lines, each line contains three integers X,k,t(0t106,1X,k106)

For each text case,we assure that it's possible to make X become 1。
 

Output
For each test case, output the answer.
 

Sample Input
  
  
2 9 2 1 11 3 3

 

Sample Output
  
  
4 3
 

Source
 
题意:
    给你一个数X,对这个X有两种操作:1,X-i (0<i<=t)  2,如果X%k==0   X/=k  问你最少操作多少次可以使X变成1
刚开始以为是贪心,结果发现被HANK掉了,后来看题解是道DP,很好找到状态和状态转移方程,dp[i]表示为1到i的最小操作次数,dp[i]=min(dp[i-k])(1<=k<=t).如果i%k==0,
dp[i]=min(dp[i],dp[i/k]). 但是这样时间复杂度会到达O(X*t)明显超时,只好用单调队列优化。(至于单调队列,不懂的话去百度吧。)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <queue>
#include <vector>
#define inf 0x6fffffff
#define LL long long
#define mem(p,k) memset(p,k,sizeof(p));
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;

int dp[1000005],que[1000005];

int main()
{
    int m;
    cin>>m;
    while(m--){
        int x,k,t,head=1,tail=1;
        cin>>x>>k>>t;
        if(x==1){
            cout<<0<<endl;
            continue;
        }
        if(t>=x-1){
            cout<<1<<endl;continue;
        }
        if(t==0){
            int sum=0;
            while(x!=1){
                x/=2;
                sum++;
            }
            cout<<sum<<endl;continue;
        }
        mem(que,0);
        mem(dp,0);
        que[tail++]=1;
        for(int i=2;i<=x;i++){
            while(tail>head&&i-t>que[head])head++;
            if(tail>head)dp[i]=dp[que[head]]+1;
            if(i%k==0)dp[i]=min(dp[i],dp[i/k]+1);
        
            while(tail>head&&dp[i]<dp[que[tail-1]])tail--;
            que[tail++]=i;
           // cout<<i<<" ";
        }
        cout<<dp[x]<<endl;
    }
    return 0;
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值