usOJ

( ext{Solution})

显然因为乘号加号优先级不同,我们同时 (dp) 这次加入了乘号会破坏之前算出的加号段。

可以考虑先把乘号算出来,再用加号合并。

(f[i][j][k]) 表示 ([i,j]) 内数字为 (k) 最少加多少个乘号,(g[i][k]) 表示前 (i) 个位置得到数字 (k) 最少符号。大力 (dp) 即可。

关于 (f) 数组需要注意的是乘积为 (0) 的情况。

身边的强强友情提醒 (T) 的范围是 (250) (QwQ)

( ext{Code})

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
    T x=0; int f=1; char s;
    while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
    while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
    return x*f;
}
template <class T> inline void write(const T x) {
    if(x<0) return (void) (putchar('-'),write(-x));
    if(x>9) write(x/10);
    putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T gcd(const T x,const T y) {return y?gcd(y,x%y):x;}
template <class T> inline T lcm(const T x,const T y) {return x/gcd(x,y)*y;}
template <class T> inline T Swap(T &x,T &y) {x^=y^=x^=y;}

#include <cstring>

char s[30];
int n,t,f[30][30][255],g[30][255];

int get(int l,int r) {
	int ret=0;
	rep(i,l,r) {
		ret=(ret<<1)+(ret<<3)+(s[i]^48);
		if(ret>t) return -1;
	}
	return ret;
}

int main() {
	int num;
	while(233) {
		scanf("%s",s+1); n=strlen(s+1);
		t=read(9);
		if(t==-1) break;
		memset(f,0x3f,sizeof f); memset(g,0x3f,sizeof g);
		rep(i,1,n) f[i][i][s[i]^48]=0;
		rep(len,2,n) {
			rep(i,1,n-len+1) {
				int j=i+len-1;
				num=get(i,j);
				if(~num) f[i][j][num]=0;
				rep(d,i,j-1) f[i][j][0]=Min(f[i][j][0],Min(f[i][d][0],f[d+1][j][0])+1);
				rep(k,1,t)
					rep(d,i,j-1) {
						num=get(d+1,j);
						if(num>0&&(k%num==0)) f[i][j][k]=Min(f[i][j][k],f[i][d][k/num]+1);
					}
			}
		}
		rep(i,1,n) rep(j,0,t) g[i][j]=f[1][i][j];
		rep(i,1,n) rep(k,0,t) rep(j,1,i-1) rep(val,0,k) g[i][k]=Min(g[i][k],g[j][val]+f[j+1][i][k-val]+1);
		print(g[n][t]==0x3f3f3f3f?-1:g[n][t],'
');
	}
	return 0;
}
原文地址:https://www.cnblogs.com/AWhiteWall/p/13869619.html