Terminate call after calling instance 'std :: bad_alloc' what (): std :: bad_alloc Aborted

I get an exception bad_allocin my program.

These are the limitations:

  • 1 <= T <= 10
  • The length of each line is not more than 100,000 and contains only lowercase characters.

With these limitations, I cannot understand why my program receives bad_alloc.

#include <string>
#include <algorithm>
#include <iostream>
#include <vector>

class SuffixArray {
    std::vector<std::string> suffixes;
    size_t N;
public:
    SuffixArray(std::string& s) {
        N = s.length();
        suffixes.resize(N);
        for (size_t i = 0; i < N; i++)
            suffixes[i] = s.substr(i);
        std::sort(suffixes.begin() , suffixes.end());
    }
    ~SuffixArray() {
    }
    size_t lcp(std::string& s, std::string& t) {
        size_t N = std::min(s.length(), t.length());
        for (size_t i = 0; i < N; i++)
            if (s[i] != t[i]) 
                return i;
        return N;
    }    
};

int main ( int argc, char **argv) {
    int T;
    std::cin >> T;
    std::vector<size_t> results;

    for ( int i = 0; i < T; i++) { 
        std::string str;
        std::cin >> str;
        SuffixArray sa(str);
        size_t sol = 0;

        for ( std::string::iterator it = str.begin(); it != str.end(); ++it) {
            std::string target = std::string(it, str.end());
            sol += sa.lcp(str, target);            
        }
        results.push_back(sol);
    }
    for ( std::vector<size_t>::iterator it = results.begin(); it != results.end(); ++it) 
        std::cout << *it << std::endl;
    results.clear();

    return 0;
}
+5
source share
1 answer

Because you are here:

  for (size_t i = 0; i < N; i++)
        suffixes[i] = s.substr(i);

: Create Nsubstrings of lengths 0, 1, 2, ..., N The total amount of memory that they will consume is: 1 + 2 + 3 + ... + Nbytes. Having the good old Gauss at hand, you will find that the sum of the first numbers N:N * (N + 1) / 2

, N = 100 000, 5 - , . 2 , , 64- .

: , , , :

: SuffixArray, , - lcp, suffixes. , ?

+15

All Articles