先预处理出从i 开始 和 从 j 开始的lcp, 然后直接dp
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 5000 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} char s[N]; int n; short lcp[N][N]; int dp[N][N]; int sum[N][N]; int ansWay, ansLen = inf; int bin[N]; int main() { for(int i = bin[0] = 1; i < N; i++) bin[i] = 2 * bin[i - 1] % mod; scanf("%s", s + 1); n = strlen(s + 1); for(int i = n; i >= 1; i--) { for(int j = n; j > i; j--) { if(s[i] == s[j]) lcp[i][j] = 1 + lcp[i + 1][j + 1]; else lcp[i][j] = 0; } } for(int i = 1; i <= n; i++) { dp[i][1] = sum[i][1] = 1; for(int j = 2; j <= i; j++) { if(s[j] == '1') { int len = i - j + 1; if(len > 1) dp[i][j] = (dp[i][j] + sum[j - 1][j - 1] - sum[j - 1][max(j - len, 0)] + mod) % mod; if(j - len >= 1) { int sameLen = lcp[j - len][j]; if(sameLen >= len || s[j + sameLen] >= s[j - len + sameLen]) dp[i][j] = (dp[i][j] + dp[j - 1][j - len]) % mod; } } sum[i][j] = (dp[i][j] + sum[i][j - 1]) % mod; } } ansWay = sum[n][n]; memset(dp, 0x3f, sizeof(dp)); memset(sum, 0x3f, sizeof(sum)); for(int i = 1; i <= n; i++) { for(int j = i; j >= 2; j--) { if(s[j] == '1') { int len = i - j + 1; if(len > 1) chkmin(dp[i][j], sum[j - 1][min(j - 1, len - 1)] + 1); if(j - len >= 1) { int sameLen = lcp[j - len][j]; if(sameLen >= len || s[j + sameLen] >= s[j - len + sameLen]) { chkmin(dp[i][j], dp[j - 1][j - len] + 1); } } } sum[i][i - j + 1] = min(sum[i][i - j], dp[i][j]); } dp[i][1] = 1; sum[i][i] = min(sum[i][i - 1], dp[i][1]); } int now = 0; for(int i = 1; i <= n; i++) { int p = n - i + 1; if(s[p] == '1') now = (now + bin[i - 1]) % mod; if(dp[n][p] == inf) continue; if(i >= 20) { if(ansLen == inf) ansLen = (now + dp[n][p]) % mod; break; } chkmin(ansLen, now + dp[n][p]); } printf("%d %d", ansWay, ansLen); return 0; } /**/