*洛谷 P1018 [NOIP2000 提高组] 乘积最大(dfs+高精度)

  • 说在前头
  • 此篇题解是记录自己的暴力写法,并不能100分满分通过洛谷测试数据(只有60)
  • 纯纯记录写法而写

https://www.luogu.com.cn/problem/P1018

我还说这么简单呢这题,想太多嘻嘻

题目大意:

输入一个长度为n的数字s,让我们在这个数字之间插入k个×(乘以),

让我们求被乘号分割开的所有数据的总乘积的最大值。
输入 #1 
4  2
1231
输出 #1 
62

我们的数字长度为n,首尾不可超出界限,所以可以填充的位置就只有[1,n-1];
每个位置面临着选和不选,同时状态还需要回溯

  • wa点在于无法表示超长数字,需要用到高精度
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18;
const LL N=200200,M=2002;
LL n,k,maxn=0;
string s;
LL st[N];
void dfs(LL num,LL idx)
{
    if(num==k+1)
    {
        LL ans=1;
        string c;
        for(LL i=1;i<=k;i++)
        {
            //cout<<st[i]<<" ";
            if(i==1) c=s.substr(0,st[1]);
            else c=s.substr(st[i-1],st[i]-st[i-1]);
            ans*=stol(c);
        }
        ans*=stol(s.substr(st[k],n-st[k]));
        maxn=max(maxn,ans);
        return ;
    }
    for(LL i=idx;i<=n-1;i++)
    {
        st[num]=i;
        dfs(num+1,i+1);
        st[num]=0;
    }
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n>>k;
        cin>>s;
        //从[1,n-1]的数字中寻找k位
        dfs(1,1);//从第一个位置开始放,从数字1开始放
        cout<<maxn<<endl;
    }
    return 0;
}
/*
5 3
12345
1 2 3
1 2 4
1 3 4
2 3 4
*/
posted @ 2022-10-05 19:42  高尔赛凡尔娟  阅读(155)  评论(0编辑  收藏  举报