such that size of A is m and size of B is n
You need to find the k th largest sum (a+b) where a is taken from A and b is taken from B. such that k < m*n
It can be done in O(n*n) but it can also be done in really optimal way.
a[m]+b[n]>a[m-1]+b[n]>a[m-1]+b[n-1]
a[m]+b[n]>a[m]+b[n-1]>a[m-1]+b[n-1]
so a[m]+b[n] has two children a[m-1]+b[n] and a[m]+b[n-1]
typedef struct node
{
int val;
int idx1;
int idx2;
}N;
void foo(int* a, int* b, int lena, int lenb, int k)
{
int c=1;
priority_queue
pq.push(a[m]+b[n],m,n);
while(!q.empty())
{
N t=pq.pop();
c++;
if(c==k)
print(t.m,t.n);
pq.push(a[t.m-1]+b[t.n],t.m-1,t.n);
pq.push(a[t.m]+b[t.n-1],t.m,t.n-1);
}
}
Complexity?
ReplyDelete