jeudi 26 mars 2015

count number of 101 in a string

Here is the question: we need to count number of 101 in a string composed of 0s and 1s only. 101 is any subsequence of the string.



Ex: 10101 has 4 101 in it.



I'm pretty sure that I solved it correctly. For each zero I precalculate number of 1 before it and after it then multiply the answers then add the result to res.


The code is giving me wrong answer for a test case composed of a string of length 1000000.


I would like to know where is the problem in my code?


Input for the Test Case: http://ift.tt/1C9AISJ


Output shoud be 18446708952791232852 but my code is giving 22531786


Here is my code:



char s[1000005];

unsigned long long ans, res, a[1000005];

int main()
{
int n;

scanf("%s", s);
n = strlen(s);

a[0] = 0; res = 0;
for(int i = 1;i <= n;++i)
a[i] = a[i - 1] + (s[i - 1] == '1');

for(int i = 1;i <= n;++i)
if(s[i - 1] == '0') {
ans = a[n] - a[i];
ans *= a[i - 1];
res += ans;
//if(ans < 0 || res < 0) printf("%lld %lld\n", ans, res);
}

printf("%llu\n", res);


return 0;
}

Aucun commentaire:

Enregistrer un commentaire