COOLING: Getting rte

Hi , i wrote the solution code for Cooling Pies question at :

http://www.codechef.com/problems/COOLING

The code seems to be fine and is working for given test cases , But it’s giving a runtime error. Im compiling the code for C++(gcc-4.3.2). The code is as follows :

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

int main()
{
    int t,temp;
    int count=0;
    cin>>t;
    vector<int> pies;
    vector<int> racks;

    for(int i=0; i<t; i++)
    {
        int n;
        cin>>n;
        for(int i2=0; i2<n; i2++)
        {
            cin>>temp;
            pies.push_back(temp);
        }

        for(int i2=0; i2<n; i2++)
        {
            cin>>temp;
            racks.push_back(temp);
        }

        sort(pies.begin(),pies.end());
        sort(racks.begin(),racks.end());


        count=0;
        while(racks.size()>0)
        {

            while(pies.at(0)>racks.at(0))
                racks.erase(racks.begin());

            if(racks.size()>0)
            {
                pies.erase(pies.begin());
                racks.erase(racks.begin());
            }
            else break;

            count++;
        }

        pies.clear();
        racks.clear();
        cout<<count<<endl;
    }
    return 0;
}

Thanks.

The bug lies in this block:

while(pies.at(0)>racks.at(0))
    racks.erase(racks.begin());

Note that there is no check to see if racks has been emptied or not. If pies[0] is very large, the rack may eventually be emptied. For example this case will give you runtime error:

1
1
100
10

When this is run, at the above block it will erase racks.begin() in the first iteration. So racks will be empty. When the code tries to access racks.at(0) again, a runtime error occurs.

So add a check for it:

while(racks.size()>0 && pies.at(0)>racks.at(0))
    racks.erase(racks.begin());
2 Likes

code seems to be fine and is working for given test cases February 2017 Printable Calendar
Ram Raj
March 2017 Printable Calendar
Radh RaniThe simplest java code (with an empty main method) gets Time limit exceeded. What is wrong? The Time limit is mentioned as 9 seconds!