0
votes

I have N integers Ai defined as A1, A2, ..., AN. I have to handle Q queries of form a. For each such query, find an index i such that Ai ≥ a. And I have to minimise the difference Ai-a. I have done it like

   while(q--)
   {
        cin>>a;
        mini=INT_MAX;
        index=-1;
        for(int i=0;i<n;i++)
        {
            diff1=A[i]-a;
            if(diff1>=0)
            {
                ll sum=diff1;
                if(sum<mini)
                {
                    mini=sum;
                    index=i+1;
                }
                if(mini==0)
                    break;
            }
        }
        cout<<index;
   }

But it leads to TLE . What is the efficient method to do it?

1
Do you need the exact position in array of Ai, or only need its value? - timrau
I need the index i of Ai element - ankit kumar
@ankitkumar Give the problem statement and problem source for ensuring it is not a part of any running contest - Enamul Hassan

1 Answers

0
votes

You could build array of pairs of (Ai, i), sort once, and binary search Q times.

#include <vector>
#include <algorithm>
#include <utility>

bool cmp1st(const std::pair<int, int>& lhs, const std::pair<int, int>& rhs)
{
    return lhs.first < lhs.right;
}

std::pair<int, int> *values = new std::pair<int, int>[n];
// Build array of (Ai, i)
for (int i = 0; i < n; ++i) {
    values[i] = std::make_pair(A[i], i);
}
// Sort by ascending order of Ai
std::sort(values, values + n);
while(q--)
{
    cin>>a;
    // binary search
    int index = std::lower_bound(values, values + n, std::make_pair(a, 0), cmp1st)->second;
    cout<<index;
}
delete [] values;