There are n concert tickets available, each with a certain price. Then, m customers arrive, one after another. Each customer announces the maximum price he or she is willing to pay for a ticket, and after this, they will get a ticket with the nearest possible price such that it does not exceed the maximum price.
Input
The first input line contains integers n and m: the number of tickets and the number of customers.
The next line contains n integers h1,h2,…,hn: the price of each ticket.
The last line contains m integers t1,t2,…,tm: the maximum price for each customer.
Output
Print, for each customer, the price that they will pay for their ticket. After this, the ticket cannot be purchased again.
If a customer cannot get any ticket, print −1.
Constraints
1 ≤ n, m ≤ 2⋅10^5
1 ≤ hi, ti ≤ 10^9
Example
Input:
5 3
5 3 7 8 5
4 8 3
Output:
3
8
-1
My approach is to sort all h1, h2, ... hn then use binary search for each ti and will mark the chosen h as inf. this will be roughly done in nlog(n) + mlog(n). Is there any better idea to do it.
I implemented the code as:
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
vector<ll> v(n);
ll p;
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
sort(v.begin(), v.end());
for (int i = 0; i < m; i++)
{
cin >> p;
if (p < v.front())
cout << -1 << "\n";
else
{ if(p>v.back()){
cout<<v.back()<<"\n";
v.pop_back();
}else{
auto it = upper_bound(v.begin(), v.end(), p);
cout << *(it-1) << "\n";
v.erase(it - 1);
}
}
}
}
it is not executing in the limited time.