简体   繁体   中英

C++ Memory Limit Exceeded when running small numbers

I am making a code for a problem on Iceland.Kattis.Com called voff in which you have to calculate the number of dogs required to produce a certain frequency of barks.

There are N barks and each dog can bark up to once every K seconds. The first line of input contains N and K, the second line contains the times at which barks were heard.

I have made a python code which is almost fast enough to get 100 points but just a little bit shy of getting there. So I decided to write the same code but in C++ (clang 7.0.0-3~ubuntu0.18.04.1) and when I run any other test case than the first one I get Memeory Limit Exceeded.

I have tried using 'long long', 'unsigned long long' and 'int' but I get Memory Limit Exceeded on all of them.

#include <bits/stdc++.h>
using namespace std;


int main() {
  int N, K;
  vector<int> barks;
  vector<int> dogs;
  dogs.push_back(0);

  cin >> N >> K;
  for(int i = 0; i < N; i++){
    int inp;
    cin >> inp;
    barks.push_back(inp);
  }


  for(int bark : barks){
    for(int i = 0; i < dogs.size(); i++){
      if (bark >= dogs[i]){
        dogs[i] = bark + K;
        break;
      } else {
        dogs.push_back(bark + K);
      }
    }
  }
  cout << dogs.size() << endl;
}

When inputting the first test case the output is and should be '1'. But when running any other test case the it Exceeds the Memory Limit.

You end up with an infinite number of dogs as each dog you add in the for i loop fails the bark >= dogs[i] test which causes another dog to be added and so on.

Changing your code to only add one dog when no dogs match the condition works:

for (int bark : barks) {
    bool found = false;
    for (int i = 0; i < dogs.size(); i++) {
        if (bark >= dogs[i]) {
            dogs[i] = bark + K;
            found = true;
            break;
        }
    }
    if (!found)
    {
        dogs.push_back(bark + K);
    }
}

PS don't use #include <bits/stdc++.h> , it is non standard and only works on some platforms, include just the c++ headers you need (eg <iostream> and <vector> ) instead. using namespace std can also cause issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM