-2

I'm writing this code to optimize the time of the problem and it is a dp problem

Given string S is: 574674546476

for index 1: Number of even numbers from 5 to end of the string is 7 so the result of index 1 is 7.

for index 2: Number of even numbers from 7 to end of the string is 7 so the result of index 2 is 7.

for index 3: Number of even numbers from 4 to end of the string is 7 so the result of index 3 is 7.

for index 3: Number of even numbers from 6 to end of the string is 6 so the result of index 4 is 6.

...

This is the code which I've tried but it shows segmentation fault in this code

#include <bits/stdc++.h>
using namespace std;
int main()
{
    char str[10005];
    int i;
    cin >> str;
    int n = strlen(str);
    int arr[10005];
    for (i = 0; i < n; i++) {
        arr[i + 1] = str[i] - 48;
    }

    int tab[n + 1];

    if (arr[n] % 2 == 0) {
        tab[n] = 1;
    }
    else {
        tab[n] = 0;
    }

    for (i = n - 1; i >= 1; i++) {
        if (arr[i] % 2 == 0) {
            tab[i] = tab[i + 1] + 1;
        }
        else {
            tab[i] = tab[i + 1];
        }
    }
    for (i = 1; i <= n; i++) {
        cout << tab[i] << " ";
    }
}

I expect output should be

7 7 7 6 5 5 4 4 3 2 1 1

But when I'm giving input 574674546476 and I want to solve using dp I write the code, it shows segmentation fault.

t.niese
  • 39,256
  • 9
  • 74
  • 101
hack sark
  • 11
  • 5
  • The site has a preview, please use it to make your question is readable, at least add newlines between the different parts that belong together. – t.niese Aug 11 '19 at 06:42
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – melpomene Aug 11 '19 at 06:48

1 Answers1

1
      for(i=n-1;i>=1;i++){

should be

      for(i=n-1;i>=1;i--){

That explains the crash but you also have the two common errors we see when people submit competitive code

This is not a standard C++ header file

#include<bits/stdc++.h>

In this code you should be using

#include <iostream>

And this is not legal C++

int tab[n+1];

since in C++ array sizes must be compile time constants, but here n is a variable. You should use

#include <vector>

and

vector<int> tab(n+1);

instead.

john
  • 85,011
  • 4
  • 57
  • 81