0

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?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065

1 Answers1

0

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;
timrau
  • 22,578
  • 4
  • 51
  • 64
  • if i will introduce an array B similar to A and b in place of a and i want to find the minimum sum Ai-a+Bi-b, then what modifications are needed for this problem? – ankit kumar Nov 28 '15 at 17:38
  • @ankitkumar If numerical overflow is not a problem, you could build array of `(Ai + Bi, i)` and search for `(a+b, 0)`. – timrau Nov 29 '15 at 01:03