The ZCO is today and I did 5 problems to prepare for it overnight. One of the problems is the CodeChef Chewing problem.
The code takes an integer N that specifies the number of chewing gums, integer K that is the maximum hardness quotient of a pair the chewing gums possible to be eaten. This is followed by N integers that specify the hardness quotient of each type of gum. My code selects only gums with a quotient less than K and adds them to a vector. A nested for loop is used to count the number of pairs for which hardness quotient of Gum_Type1+Gum_Type2 < K.
#include <iostream>
#include <vector>
#include <algorithm>
#define ll unsigned long long int
#define speedup ios::sync_with_stdio(false); cin.tie(NULL);
using namespace std;
int main(){
speedup;
ll N,K,hq,numPairs=0;
vector<ll> hardness;
cin >> N >> K;
for(ll i=0; i< N; i++){
cin >> hq;
if (hq< K) hardness.push_back(hq);
}
sort(hardness.begin(), hardness.end());
for(vector<ll>::iterator it=hardness.begin(); it<hardness.end();it++){
for(vector<ll>::iterator it2=it+1;it2<hardness.end();it2++){
if (*it+*it2 < K) numPairs+=1;
else hardness.erase(it2);
}
}
cout << numPairs<<endl;
}
For subtask 2, I'm getting TLE by 0.01s. Could somebody help me optimize this code? I don't want to get TLEs in the exam today.
where I'm getting TLE by 0.01s
- that's a misconception, more likely than not: seeing your process exceeding the time limit, it gets it's plug pulled - no way of knowing if it would terminate in minutes, months or aeons. \$\endgroup\$