-3

I have to create a program, which counts bursted baloons, like from ZUMA. If I have a line with 3 or more baloons with the same color this sequence will burst. So in input, I have number of ballons (3 <= N <= 10^5) , and line with numbers (line with baloons color (1 <= сi <= 100) ), with 1 sequence for sure. I have to output number of bursted baloons. I have a programm, but it is working longer than 4000msv sometimes. How can I make it working faster?

  #include <iostream>
#include <string>
#include <vector>
using namespace std;


int Fmax(int n, const string& f){
int  max;
vector<int> k(n);

int i, j, p = 0;
for (i = 0; i <= n; i++)
{
    k[i] = 0;
}

for (i = 0; i <= n; i++)
{
    for (j = i; j <= n; j++)
    {

        if (f[i] == f[j])
        {
            k[p]++;

        }
        else break;
    }
    p++;
}

max = k[0];
for (i = 0; i <= p; i++){ if (max <= k[i]){ max = k[i]; } }
return max;
}
string pog(int n){
int d;
string doa;
for (int i = 1; i <= n; i++){
    cin >> d;
    doa += (char)d;
}

return doa;
}
void main(){
int i, sc = 1, bf = 1;
string f;
int len;
cin >> i;
f = pog(i);
len = i;

while (Fmax(f.length(), f) >= 3){

    for (int c = 1; c <= f.length(); c++){

        if (f[c] == f[c - 1]){
            if (sc == 1){ bf = c - 1; }
            sc++;
        }
        else{
            if (sc >= 3){ f.erase(bf, sc);  sc = 1; break; }
            sc = 1;
        }



    }
}
cout << len - f.length() << endl;


}

Any help is warmly welcome.

pguetschow
  • 5,176
  • 6
  • 32
  • 45

2 Answers2

2

You are leaking memory. Use vectors to avoid that.

Why do you need to create array? Why not use the string directly?

Pass strings which aren't modified by const reference to avoid copies.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
0

Use constant variables for the lengths:

const unsigned int f_length = f.length();
while (Fmax(f_length, f) >= 3){

  for (int c = 1; c <= f_length ; c++){

This helps the compiler reduce the number of calls to the length method.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154