Limak is a little polar bear. In the snow he found a scroll with the ancient prophecy. Limak doesn't know any ancient languages and thus is unable to understand the prophecy. But he knows digits!
One fragment of the prophecy is a sequence of n digits. The first digit isn't zero. Limak thinks that it's a list of some special years. It's hard to see any commas or spaces, so maybe ancient people didn't use them. Now Limak wonders what years are listed there.
Limak assumes three things:
- Years are listed in the strictly increasing order;
- Every year is a positive integer number;
- There are no leading zeros.
Limak is going to consider all possible ways to split a sequence into numbers (years), satisfying the conditions above. He will do it without any help. However, he asked you to tell him the number of ways to do so. Since this number may be very large, you are only asked to calculate it modulo 109 + 7.
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of digits.
The second line contains a string of digits and has length equal to n. It's guaranteed that the first digit is not '0'.
Print the number of ways to correctly split the given sequence modulo 109 + 7.
6 123434
8
8 20152016
4
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#define maxn 5005
#define MOD 1000000007
using namespace std;
typedef long long ll;
char str[maxn];
char s1[maxn],s2[maxn];
int n, dp[maxn][maxn];
int d[maxn][maxn];
void Init(){
for(int i = n-1; i >= 0; i--)
for(int j = n-1; j >= 0; j--)
if(str[i] != str[j])
d[i][j] = 0;
else
d[i][j] = d[i+1][j+1] + 1;
}
bool judge(int k1, int k2, int p1, int p2){
if(p2 - p1 > k2 - k1)
return true;
int p = d[k1][p1];
if(p > k2 - k1)
return false;
if(str[k1+p] < str[p1+p])
return true;
return false;
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d%s", &n, str);
Init();
for(int i = n-1; i >= 0; i--){
if(str[i] != '0'){
dp[i][n-1] = 1;
int h = (i + n - 1) / 2;
if((i + n - 1) % 2 == 0)
h--;
for(int j = h; j >= i; j--){
if(str[j+1] != '0'){
for(int t = j+1+j-i; t < n; t++){
if((t == n-1 || str[t+1] != '0') && judge(i, j, j+1, t)){
dp[i][j] = ((ll)dp[i][j] + dp[j+1][t]) % MOD;
break;
}
}
}
}
for(int j = n-2; j >= i; j--)
dp[i][j] = ((ll)dp[i][j] + dp[i][j+1]) % MOD;
}
}
printf("%d\n", dp[0][0]);
return 0;
}