Finding Minimal lexicographical Array - c++

I tried solving this interview question. My code runs for test cases but fails for all the real input test cases. I tried hard to find the mistake but unable to do so. Please find my code below the question
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task. He gives Bob an array and an integer K. The challenge is to produce the lexicographical minimal array after at most K-swaps. Only consecutive pairs of elements can be swapped. Help Bob in returning the lexicographical minimal array possible after at most K-swaps.
Input: The first line contains an integer T i.e. the number of Test cases. T test cases follow. Each test case has 2 lines. The first line contains N(number of elements in array) and K(number of swaps). The second line contains n integers of the array.
Output: Print the lexicographical minimal array.
Constraints:
1 <= T <= l0
1 <= N,K <= 1000
1 <= A[i] <= 1000000
Sample Input (Plaintext Link)
2
3 2
5 3 1
5 3
8 9 11 2 1
Sample Output (Plaintext Link)
1 5 3
2 8 9 11 1
Explanation
After swap 1:
5 1 3
After swap 2:
1 5 3
{1,5,3} is lexicographically minimal than {5,1,3}
Example 2:
Swap 1: 8 9 2 11 1
Swap 2: 8 2 9 11 1
Swap 3: 2 8 9 11 1
#include <iostream>
using namespace std;
void trySwap(int a[], int start, int end, int *rem)
{
//cout << start << " " << end << " " << *rem << endl;
while (*rem != 0 && end > start)
{
if (a[end - 1] > a[end])
{
swap(a[end - 1], a[end]);
(*rem)--;
end--;
}
else end--;
}
}
void getMinimalLexicographicArray(int a[], int size, int k)
{
int start , rem = k, window = k;
for (start = 0; start < size; start++)
{
window = rem;
if (rem == 0)
return;
else
{
//cout << start << " " << rem << endl;
int end = start + window;
if (end >= size)
{
end = size - 1;
}
trySwap(a, start, end, &rem);
}
}
}
int main()
{
int T, N, K;
int a[1000];
int i, j;
cin >> T;
for (i = 0; i < T; i++)
{
cin >> N;
cin >> K;
for (j = 0; j < N; j++)
{
cin >> a[j];
}
getMinimalLexicographicArray(a, N, K);
for (j = 0; j < N; j++)
cout << a[j] << " ";
cout << endl;
}
return 0;
}

Python solution can be easily translated to C++:
def findMinArray(arr, k):
i = 0
n = len(arr)
while k > 0 and i < n:
min_idx = i
hi = min(n, i + k + 1)
for j in range(i, hi):
if arr[j] < arr[min_idx]:
min_idx = j
for j in range(min_idx, i, -1):
arr[j - 1], arr[j] = arr[j], arr[j - 1]
k -= min_idx - i
i += 1
return arr

Here are two failed test cases.
2
2 2
2 1
5 3
3 2 1 5 4
In the first, your code makes no swaps, because K >= N. In the second, your code swaps 5 and 4 when it should spend its third swap on 3 and 2.
EDIT: the new version is still too greedy. The correct output for
1
10 10
5 4 3 2 1 10 9 8 7 6
is
1 2 3 4 5 10 9 8 7 6
.

Related

Having trouble printing a series

Here's the problem statement for what I'm supposed to do:
Write a program to print the following series up to the term input by user.
0, 1, 1, 2, 3, 5, 8, 13, ….
Where 0 is 1st term and 13 is 8th term.
Hint: 0, 1
0+1 = 1
0, 1, 1
1+1 = 2
0, 1, 1, 2
And here's my code:
int prev_i = 0;
cout << "Enter a number: " << endl;
cin >> number;
for (i = 0; i <= number; i++)
{
cout << prev_i + i << " ,";
prev_i = i;
}
I do get what is wrong with my code though. It adds i to prev_i then prev_i is set to i. So in the next iteration when i is 1 thats i + prev_i = 1 so now prev_i = 1 and here's the problem i is 2 now so i + prev_i = 3. And I really can't seem to figure out how to get 1 instead of 3 as the output here and so on.
Oh and don't worry about i not declared properly. I just didn't copy that part.
pls help!
You're trying to generate a fibonacci sequence (starts with two terms (0,1), and each subsequent term is the addition of the prior two). Therefore, i should not be part of the calculation; it is only there to control looping.
A simple generation of the first ten numbers in the sequence is simply this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a=0, b=1;
for (int i=0; i<10; ++i)
{
printf("%d ", a);
int c = a+b;
a = b;
b = c;
}
fputc('\n', stdout);
return EXIT_SUCCESS;
}
That's it. The code above will generate the following:
0 1 1 2 3 5 8 13 21 34
I leave applying the above logic to generate whatever your final requirements are up to you, but that's how the sequence is iteratively generated.
PS: Apologies in advance for writing C code. I totally spaced the language tag, but nonetheless the algorithm is the same.
The shown series is the fibonacci sequence.
Look at its definition and find out: Which numbers do you need to compute the current one?
In your current code, you only have one previous number available.
If that's not enough, what else might you need?
Here are my three cents.:)
#include <iostream>
#include <utility>
int main()
{
while (true)
{
std::cout << "Enter a non-negative number (0 - exit): ";
unsigned int n;
if (!( std::cin >> n ) || ( n == 0 )) break;
unsigned long long int first = 0;
unsigned long long int second = 1;
std::cout << '\n';
for (unsigned int i = 0; i < n; i++)
{
if (i != 0) std::cout << ' ';
std::cout << first;
second += std::exchange( first, second );
}
std::cout << "\n\n";
}
}
The program output might look like
Enter a non-negative number (0 - exit): 1
0
Enter a non-negative number (0 - exit): 2
0 1
Enter a non-negative number (0 - exit): 3
0 1 1
Enter a non-negative number (0 - exit): 4
0 1 1 2
Enter a non-negative number (0 - exit): 5
0 1 1 2 3
Enter a non-negative number (0 - exit): 6
0 1 1 2 3 5
Enter a non-negative number (0 - exit): 7
0 1 1 2 3 5 8
Enter a non-negative number (0 - exit): 8
0 1 1 2 3 5 8 13
Enter a non-negative number (0 - exit): 0
Fibonacci numbers grow very quickly. So in general you need to check whether an overflow can occur in the for loop or not.
Your code is printing the sum of current and just previous element. But the above question asks for the Fibonacci number which is define as:
Fib[i] = Fib[i - 1] + Fib[i - 2]; Fib[0] = 0, Fib[1] = 1
Now it can be solved through recursion or 1D DP.
But a simple solution can be constructed by knowing the above relation. We can define the current Fibonacci number is the sum of just previous and previous of just previous.
The code is:
int prev1 = 0; // Fib[0]
int prev2 = 1; // Fib[1]
int curr;
cout << prev1 << ' ' << prev2 << ' ';
for (int i = 2; i <= n; i++)
{
// Fib[i] = Fib[i - 1] + Fib[i - 2];
curr = prev2 + prev1;
cout << curr << ' ';
prev1 = prev2;
prev2 = curr;
}

draw ascii square spiral c++ with a filling in it (Output on terminal itself)

I have been desperately looking for a definite answer for this. The challenge was beyond my thinking scope or wasn't enough.
There was something topic like Spiral, but mostly is about matrix. If it is about the ascii art, nothing answer look's like this problem I have.
Suppose you have an integer N
int N;
Now, I input the N with an integer value
scanf("%d", N); fflush(stdin);
Let's see some examples:
1
#
5
#####
....#
###.#
#...#
#####
9
#########
........#
#######.#
#.....#.#
#.###.#.#
#.#...#.#
#.#####.#
#.......#
#########
11
###########
..........#
#########.#
#.......#.#
#.#####.#.#
#.#...#.#.#
#.#.###.#.#
#.#.....#.#
#.#######.#
#.........#
###########
and so on.
I have a difficulty to understand and write the algorithm for it.
I had tried to search for help but none of them fit my expectation.
Here are some of the last attempts
Attempt A
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void Spirality(int N, char Border, char Fill) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < i; j++) {
printf("%c", Border);
for (int k = 0; k < j; k++) {
printf("%c", Fill);
}
};
printf("\n");
};
};
int main() {
int N;
char Out = '#', In = '.';
char A[101][101];
scanf("%d", &N); fflush(stdin);
int len = N, k = 1, p = 0, i;
Spirality(N, Out, In);
printf("\n");
getchar();
return 0;
}
Result: N is 5
5
#
##.
##.#..
##.#..#...
Attempt B
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void Spirality(int N, char Border, char Fill) {
for (int i = 0; i < N; i++) {
for (int i = 0; i < N; i++) printf("%c", Border);
printf("\n");
for (int i = 0; i < N; i++) printf("%c", Fill);
};
};
int main() {
int N;
char Out = '#', In = '.';
char A[101][101];
scanf("%d", &N); fflush(stdin);
Spirality(N, Out, In);
printf("\n");
getchar();
return 0;
}
Result: N is 5
#####
.....#####
.....#####
.....#####
.....#####
.....
None of these output expected spiral.
At first, let's take a look at what your program has to output (line by line).
When N = 11, the output should be like (next to the "image" I will write configuration of your signs):
########### 11
..........# 10 1
#########.# 9 1 1
#.......#.# 1 7 1 1 1
#.#####.#.# 1 1 5 1 1 1 1
#.#...#.#.# 1 1 1 3 1 1 1 1 1
#.#.###.#.# 1 1 1 1 3 1 1 1 1
#.#.....#.# 1 1 1 5 1 1 1
#.#######.# 1 1 7 1 1
#.........# 1 9 1
########### 11
The line 1 7 1 1 1 means that at first one sign (#) has to be written, then 7 signs (.), and then 3x one sign (.#.).
Because all of our lines starts and ends with ones, and there is only one number, different from one in each line, we can simplify our problem (output) like this:
11
10 1
9 2
1 7 3
2 5 4
3 3 5
4 3 4
3 5 3
2 7 2
1 9 1
11
Note that in each line, except 2nd one, the first character is '#'.
So the function for the one line of output can look like that:
const char sign[2] = { '#', '.' };
void outputline(int l, int m, int r, int currsign) {
int i;
for (i = 0; i < l; i++) {
cout << sign[currsign] << ' ';
currsign = (currsign + 1) % 2;
}
for (i = 0; i < m; i++) cout << sign[currsign] << ' ';
currsign = (currsign + 1) % 2;
for (i = 0; i < r; i++) {
cout << sign[currsign]<<' ';
currsign = (currsign + 1) % 2;
}
cout << endl;
}
In the function, the first argument tells us, with how many ones line begins, m is the only number in the line that is not 1, r tells us with how many ones line ends and currsign is the index of the character that the line begins with.
Now the problem is reduced on how 3 numbers changes from line to line. If I copy paste it from above:
l m r
0 11 0
0 10 1
0 9 2
1 7 3
2 5 4
3 3 5
4 3 4
3 5 3
2 7 2
1 9 1
0 11 0
We can see, that the first 2 lines are a bit special (and therefore can be written separately). But for all other lines we can see simple rule.
Until m is not 3, it decreases for 2 in every steps, while l and r increase for 1.
In the next step, m is 3 again, while l increases for 1 and r decreases for 1
And after that, until m is not N (11 in our case), m increases for 2 in every step, while l and r decrease for 1.
This algorithm works for every odd number.
You can do the same thing to see what are the patterns for each N(length of the side) divisible by 4 and for each N of the form 4*k+2.
So the main function should look like:
int main() {
int N, n;
cin >> N;
int left = 0, middle = N, right = 2;
if (N % 4 == 0) n = 4;
else n = 2;
outputline(0, middle--, 0, 0);
if (middle == 0) return 0;
outputline(0, middle--, 1, 1);
if (middle == 0) return 0;
for(middle; middle >=n; middle -=2)
outputline(left++, middle, right++, 0);
if (N % 2 == 1) {
middle += 2; right -= 2;
}
else if (N % 4 == 2) {
left--; middle += 4; right-=3;
}
else if (N % 4 == 0) {
left++; right--;
}
for (middle; middle <= N; middle += 2)
outputline(left--, middle, right--, 0);
return 0;
}
Hope that the answer helps you.

Pattern Printing-Where am I going wrong in this C++ code?

I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}

Brute Force Permutation Swapping

I've been working on a brute force algorithm to generate all permutations of a given set. Eventually, I want to feed each of these permutations into a nxn matrix to test if it is a valid magic square or not.
--I KNOW THAT THERE IS A WAY TO GENERATE A MAGIC SQUARE EASILY--
That is not what I want to do, though. I'm focusing on the brute force aspect of it.
For a set of 3 elements, it works wonderfully. However, once I use 4 or more elements, I lose out on a few permutations. Just from looking at the output of 4, I am missing 7 permutations.
#include <stdio.h>
#include <iostream>
using namespace std;
//ms = magic square
//n = size
void perm(int ms[], int n) {
int pivot = 0;
int index = 0;
int pivBit = 1;
int fin = 0;
int hold = 0;
//While we are not finished
while (fin == 0) {
//Incriment the index
++index;
if (index >= n) {
index = 0;
}
//if index is equal to the pivot
if (index == pivot) {
//Is this the first time visiting the pivot?
if (pivBit == 0) {
//Are we at the beginning again?
if (index == 0 && pivot == 0)
{
fin = 1;
}
pivBit = 1;
++index;
}
//Second time visiting?
else {
pivBit = 0;
++pivot;
if (pivot >= n) {
pivot = 0;
}
}
}
//If we are out of bounds
if (index >= n) {
index = 0;
}
//swap
hold = ms[index];
ms[index] = ms[pivot];
ms[pivot] = hold;
for (int i = 0; i < n; ++i) {
cout << ms[i];
if (i < n - 1) {
cout << ", ";
}
else {
cout << endl;
}
}
}
}
int main() {
cout << "Are you ready to brute force, my brother?" << endl;
//Set
int magicsquare[] = { 1, 2, 3, 4};
int size = 4;
perm(magicsquare, size);
getchar();
return 0;
}
My output is:
2 1 3 4
3 1 2 4
4 1 2 3
1 4 2 3
1 2 4 3
1 3 4 2
3 1 4 2
3 4 1 2
3 4 2 1
2 4 3 1
2 3 4 1
2 3 1 4
4 3 1 2
4 2 1 3
4 2 3 1
1 2 3 4
2 1 3 4
Looking at it, I can already see that I am missing both 1 4 3 2 and 1 3 2 4.
Where've I gone wrong in my algorithm?
The wiki article on permutation includes a common algorithm used to produce all permutations in lexicographic order, starting with an array of sequentially increasing integers, ending with that array reversed. wiki next permutation.
If dealing with an array of objects, you can generate an array of indices 0 through n-1 and use next permutation on the indices to produce all permutations of the array of objects.
You can also do a web search for next permutation to find similar algorithms. The recursive ones produce all permutations, but not in lexicographic order.
The simplest way to generate all permutations is recursive. For each i, swap the i'th element to the 0 position. Then recursively find all permutations of of the remaining array.
int buf[1000], n; // better to wrap these in a class...
void permute(int *a, int a_len) {
if (a_len == 1) {
for (int i = 0; i < n; i++) printf("%d ", buf[i]);
printf("\n");
} else {
for (int i = 0; i < a_len; i++) {
swap(a, 0, i);
permute(a + 1, a_len - 1);
swap(a, 0, i);
}
}
}
void run(int buf_len) {
for (int i = 0; i < buf_len; i++) buf[i] = i + 1;
n = buf_len;
permute(buf, buf_len);
}
This assumes no repeated elements in the original array. It's not to hard to have it take repeated elements into account.

Find subsequences of a string whose length is as large as 10,000

I have a string whose size can be as large as "10,000". I have to count those SUBSEQUENCES which are divisible by 9.
SUBSEQUENCE: A subsequence is an arrangement in which the order of characters of given string is maintained. For ex: if given string is 10292 then some of its subsequences are 1, 102, 10, 19, 12, 12(12 is twice as 2 comes twice), 129, 029, 09, 092, etc. Some numbers which are not subsequences of given string are: 201(2 and 0 can't come before 1), 921, 0291, etc.
I have tried to generate all subsequences(powerset) of given string using bit shifting and checking each string if it is divisible by 9. But this works fine as long as length of string is <=10. After that, I don't get proper subsequences(some subsequences are displayed negative numbers).
Below is my code:
scanf("%s", &str); //input string
int n=strlen(str); //find length of string
//loop to generate subsequences
for(i=1;i<(1<<n);++i){
string subseq;
for(j=0;j<n;++j){
if(i&(1<<j)){
subseq+=str[j]; // generate subsequence
}
}
//convert generated subseq to int; number is 'long' tpye
number=atol(subseq.c_str());printf("%ld\n", number);
//ignore 0 and check if number divisible by 9
if(number!=0&&number%9==0)count++;
}
printf("%ld\n", count);
Since a number is divisible by nine if and only if the sum of its digits is divisible by nine, you can get away with this problem with a O(n) recursive algorithm.
The idea is the following: at each step, split in two the subsequence and determine (recursively) how many sequences have the sum of its digits be i % 9, where i ranges from 0 to 8. Then, you build up this very same table for the whole range by "merging" the two tables in O(1) in the following way. Let's say L is the table for the left split and R for the right one and you need to build the table F for the whole range.
Then you have:
for (i = 0; i < 9; i++) {
F[i] = L[i] + R[i];
for (j = 0; j < 9; j++) {
if (j <= i)
F[i] += L[j] * R[i - j]
else
F[i] += L[j] * R[9 + i - j]
}
}
The base case for a subsequence of only one digit d is obvious: just set F[d % 9] = 1 and all the other entries to zero.
A full C++11 implementation:
#include <iostream>
#include <array>
#include <tuple>
#include <string>
typedef std::array<unsigned int, 9> table;
using std::tuple;
using std::string;
table count(string::iterator beg, string::iterator end)
{
table F;
std::fill(F.begin(), F.end(), 0);
if (beg == end)
return F;
if (beg + 1 == end) {
F[(*beg - '0') % 9] = 1;
return F;
}
size_t distance = std::distance(beg, end);
string::iterator mid = beg + (distance / 2);
table L = count(beg, mid);
table R = count(mid, end);
for (unsigned int i = 0; i < 9; i++) {
F[i] = L[i] + R[i];
for(unsigned int j = 0; j < 9; j++) {
if (j <= i)
F[i] += L[j] * R[i - j];
else
F[i] += L[j] * R[9 + i - j];
}
}
return F;
}
table count(std::string s)
{
return count(s.begin(), s.end());
}
int main(void)
{
using std::cout;
using std::endl;
cout << count("1234")[0] << endl;
cout << count("12349")[0] << endl;
cout << count("9999")[0] << endl;
}
I had an idea!
Since you only have to count the substrings, you don't care what they actually are. So instead, you can just store counts of their possible sums.
Then, what if you had a function that could combine the count tables of two substring sets, and give you the counts of their combinations?
And since I know that was a horrible explanation, I'll give an example. Say you're given the number:
2493
Split it in half and keep splitting until you get individual digits:
2493
/ \
24 93
/\ /\
2 4 9 3
What can 2 sum to? Easy: 2. And 4 can only sum to 4. You can build tables of how many substrings sum to each value (mod 9):
0 1 2 3 4 5 6 7 8
2: 0 0 1 0 0 0 0 0 0
4: 0 0 0 0 1 0 0 0 0
9: 1 0 0 0 0 0 0 0 0
3: 0 0 0 1 0 0 0 0 0
Combining two tables is easy. Add the first table, the second table, and every combination of the two mod 9 (for the first combination, this is equivalent to 2, 4, and 24; for the second, 9, 3, and 93):
0 1 2 3 4 5 6 7 8
24: 0 0 1 0 1 0 1 0 0
93: 1 0 0 2 0 0 0 0 0
Then do it again:
0 1 2 3 4 5 6 7 8
2493: 3 0 2 2 2 2 2 2 0
And there's your answer, sitting there in the 0 column: 3. This corresponds to the substrings 243, 2493, and 9. You don't know that, though, 'cause you only stored counts - and fortunately, you don't care!
Once implemented, this'll give you O(n) performance - you'll just have to figure out exactly how to combine the tables in O(1). But hey - homework, right? Good luck!
If you use int then you shouldnt left shift it too much. If you do, you set the sign bit. Use unsigned int. Or dont left shift too much. You can rightshift once you done if you insist on int.
for the
printf("%ld\n", count);
printf could have problems at displaying long-int types. Did you try cout ?
Here's C++ code according to Akappa's algorithm. However this algorithm fails for numbers that contain one or more 0s i.e. in cases of "10292" and "0189" but gives correct answers for "1292" ans "189". Would appreciate it if anyone could debug this to give answers for all cases.
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<sstream>
#include<algorithm>
#include<cctype>
#include<list>
#include<set>
#include<set>
#include<map>
using namespace std;
typedef vector<int> table;
table count(string::iterator beg, string::iterator end)
{
table F(9);
std::fill(F.begin(), F.end(), 0);
if (beg == end)
return F;
if (beg + 1 == end) {
F[(*beg - '0') % 9] = 1;
return F;
}
size_t distance = std::distance(beg, end);
string::iterator mid = beg + (distance / 2);
table L = count(beg, mid);
table R = count(mid, end);
for (unsigned int i = 0; i < 9; i++) {
F[i] = L[i] + R[i];
for(unsigned int j = 0; j < 9; j++) {
if (j <= i)
F[i] += L[j] * R[i - j];
else
F[i] += L[j] * R[9 + i - j];
}
}
return F;
}
table count(std::string s)
{
return count(s.begin(), s.end());
}
int main()
{
cout << count("1234")[0] << endl;
cout << count("12349")[0] << endl;
cout << count("9999")[0] << endl;
cout << count("1292")[0] << endl;cout << count("189")[0] << endl;
cout << count("10292")[0] << endl;cout << count("0189")[0] << endl;
system("pause");
}