题解:AT_abc403_f [ABC403F] Shortest One Formula
细节真多。
显然的 dp 题。
设
-
i = j + k$ 枚举 $j$ 则中间加个等号 $f_i = \min f_j + f_{i - j} + 1 -
初始化
但是这就完了吗?
我们发现对于第二种情况,有可能是连乘的形式或者是 1,11,111,1111 的形式,这种是不用加括号的,所以可以做个括号匹配,如果存在某一个时刻满足栈空且字符是 + 的就不用括号了。
最后的最后,需要注意如果 虽然有些同学没判断也过了。
代码:
#include<iostream>
#include<cstring>
#include<stack>
const int N = 2004;
int f[N],n;
std::string g[N];
inline int calc(std::string s){
if(s == "1" || s == "11" || s == "111" || s == "1111") return s.size();
std::stack<char> st;
for(auto & it : s){
if(it == '('){
st.push('(');
}
if(it == ')'){
if(st.top() == '('){
st.pop();
}else{
return 1e9;
}
}
if(!st.size() && it == '+'){
return s.size() + 2;
}
}
return s.size();
}
inline std::string make(std::string s){
if(s == "1" || s == "11" || s == "111" || s == "1111") return s;
std::stack<char> st;
for(auto & it : s){
if(it == '('){
st.push('(');
}
if(it == ')'){
if(st.top() == '('){
st.pop();
}
}
if(!st.size() && it == '+'){
return '(' + s + ')';
}
}
return s;
}
int main(){
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin >> n;
f[1] = 1;g[1] = "1";
f[11] = 2;g[11] = "11";
f[111] = 3;g[111] = "111";
f[1111] = 4;g[1111] = "1111";
for(int i = 2;i <= n; ++ i){
if(!f[i]){
f[i] = (i << 1) - 1;
g[i] = "1";
for(int j = 1;j < i; ++ j){
g[i] += "+1";
}
}
for(int j = 0;j < i; ++ j){
if(f[i] > f[j] + f[i - j] + 1){
f[i] = f[j] + f[i - j] + 1;
g[i] = g[j] + '+' + g[i - j];
}
int need = i - j;
for(int k = 1;k * k <= need; ++ k){
if(need % k) continue;
int len = f[j] + 1 + calc(g[k]) + calc(g[need / k]) + 1 - (j == 0);
if(len < f[i]){
f[i] = len;
if(j ^ 0)
g[i] = g[j] + '+' + make(g[k]) + '*' + make(g[need / k]);
else
g[i] = make(g[k]) + '*' + make(g[need / k]);
}else{
if(len == f[i]){
std::string res = "";
if(j ^ 0)
res = g[j] + '+' + make(g[k]) + '*' + make(g[need / k]);
else
res = make(g[k]) + '*' + make(g[need / k]);
if(calc(res) <= calc(g[i])){
g[i] = res;
}
}
}
}
}
}
std::cout << g[n];
return 0;
}