I am getting runtime in my code on online judge[solved]

I am getting SIGSEGV runtime on my code on online judge but this code works fine on ideone.com please can anyone spot the error in my code

question link : SPOJ.com - Problem STAMPS

link: 2Bk11i - Online C++0x Compiler & Debugging Tool - Ideone.com

my code :

#include <bits/stdc++.h>

typedef unsigned long long ll;
using namespace std;

int main() {
ll t,n,k,a[100001],i,c,z,g;
cin>>t;
g=1;
while(t--){
    cin>>n>>k;
    for(i=0;i<k;i++){
        cin>>a[i];
    }//cout<<a[0];
    sort(a,a+n);
    reverse(a,a+n);
    i=0;
    c=1;
    z=0;
    while (c<=k){
        z+=a[i];
        if (z<n){
            i+=1;
        }
        else{
            break;
        }
        c++;
    }
    if(z>=n){
        cout<<"Scenario #"<<g<<":"<<endl<<c<<endl<<endl;
    }
    else{
        cout<<"Scenario #"<<g<<":"<<endl<<"impossible"<<endl<<endl;
    }g++;
}
return 0;

}

The value of ‘c’ might become equal to k since you have used while(c<=k) but a[k] is not defined. index can be k-1 (maximum).

dont know whether i am right or not, but for

sort(a,a+n);

i think it should be

sort(a,a+k)

and same for reverse() method.

Sorry if i am wrong because i am not so familiar with c++ and for reverse sort i use

sort(a.rbegin(),a.rend());
1 Like

You are allocating 10^5 for the array a , where it should be 10^6 !

1 Like

yes that works, replace ‘a+n’ with ‘a+k’ for sort() as well as reverse() methods.

@bahosain I think so
first line tells you how many stamps (from 1 to 1000000) Lucy needs to borrow

That means, 10^6 is not the size of array it is no. of stamps required and,

how many friends (from 1 to 1000) offer her some stamps.

So, Size of array should be Lucy’s number of friends willing to offer her stamps, i.e. it should be 1000