I was solving a question in a competition I joined that asked for a program that calculates how many numbers are less than \$q\$. I solved the question but didn't get the full mark because the code was too slow.
The input is 4 lines, the 1st contains \$n\$ (the length of the array), the second contains the elements of the array, the third contains how many numbers it wants the program to find out how many numbers are less than it and the fourth line contains the numbers.
I remember some of the variables can be as big as \$10^9\$.
the output is the number of numbers less than q with a space after it. there can be multiple "\$q\$"s.
here is the code I entered during the competition:
#include <iostream>
using namespace std;
int main()
{
int n,Q;
cin>>n;
int x[n];
for(int i=0;i<n;i++){
cin>>x[i];
}
cin>>Q;
for(int i=0;i<Q;i++){
int q,count=0;
cin>>q;
for(int j=0;j<n;j++){
if(q>x[j]){
count++;
}
}
cout<<count<<' ';
}
}
I have qualified for the next round and decided to revisit the question as revision so I came up with this code, unfortunately I don't know how to test how fast it is:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,Q,q;
cin>>n;
int x[n];
for(int i=0;i<n;i++){
cin>>x[i];
}
sort(x,x+n);
cin>>Q;
for(int i=0;i<Q;i++){
cin>>q;
for(int j=0;j<n;j++){
if(q<=x[j]){
cout<<j<<' ';
j+=n;
}
}
}
}