整數劃分(區間dp)__動態規劃

來源:互聯網
上載者:User

題目連結:點這裡。。。。


題意:給出兩個整數 n , m ,要求在 n 中加入m - 1 個乘號,將n分成m段,求出這m段的最大乘積。(1<=n<=1e19,m<=n的位元)


題解:

1、設dp[i][j][k]為區間[i,j]中乘號數目為k的最大乘積。

2、注意兩兩合并的時候合并為dp[i][j][0]的時候,直接合并成了一個整數沒有乘號。

3、兩兩合并的時候合并為dp[i][j][k](k!=0)的時候,我們利用乘號將他們合并起來就可以了,並且沒有遺漏。


代碼:

#include<cstdio>#include<cstring>#include<iostream>#include<sstream>#include<algorithm>#include<vector>#include<bitset>#include<set>#include<queue>#include<stack>#include<map>#include<cstdlib>#include<cmath>#define LL long long#define pb push_back#define pa pair<int,int>#define clr(a,b) memset(a,b,sizeof(a))#define lson lr<<1,l,mid#define rson lr<<1|1,mid+1,r#define bug(x) printf("%d++++++++++++++++++++%d\n",x,x)#define key_value ch[ch[root][1]][0]#pragma comment(linker, "/STACK:102400000000,102400000000")const LL  MOD = 1000000007;const int N = 100+15;const int maxn = 1e5+15;const int letter = 130;const LL INF = 1e7;const double pi=acos(-1.0);const double eps=1e-10;using namespace std;inline int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}    return x*f;}int m;LL n,b[25],dp[25][25][25],bin[25];///dp[i][j][k] 表示i-j區間裡有k個乘號的最大值int main(){    int tc;    scanf("%d",&tc);    bin[0]=1;    while(tc--){        cin>>n>>m;        m--;        clr(dp,0);        int k=0;        while(n){b[++k]=n%10,n/=10;}        reverse(b+1,b+k+1);        for(int i=1;i<=k;i++) dp[i][i][0]=b[i];        for(int len=2;len<=k;len++){            for(int i=1;i<=k;i++){                int j=i+len-1;                if(j>k) break;                dp[i][j][0]=dp[i][j-1][0]*10+dp[j][j][0];                for(int x=1;x<=min(j-i,m);x++){                    for(int y=i;y<j;y++){                        for(int z=0;z<=min(x-1,min(m,y-i));z++){                            dp[i][j][x]=max(dp[i][j][x],dp[i][y][z]*dp[y+1][j][x-z-1]);                        }                    }                }            }        }        cout<<dp[1][k][m]<<endl;    }    return 0;}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.