Task: Given two arrays A and B of size N and M respectively. Sort the array A based on elements in B. If A elements not present in B then append them at the end in sorted order.
Example:
Input:
1
11 4
2 1 2 5 7 1 9 3 6 8 8
2 1 8 3
Output:
2 2 1 1 8 8 3 5 6 7 9
Here is the Code:
Program in C++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n,m;
- cin>>n>>m;
- int a[n],b[m];
- map<int,int> rs;
- for(int i=0;i<n;i++)
- {
- cin>>a[i];
- rs[a[i]]++;
- }
- for(int i=0;i<m;i++)
- {
- cin>>b[i];
- if(rs.find(b[i])!=rs.end())
- {
- int t = rs[b[i]];
- while(t!=0)
- {
- cout<<b[i]<<" ";
- t--;
- }
- rs.erase(b[i]);
- }
- }
- for(auto i=rs.begin();i!=rs.end();i++)
- {
- while(i->second--)
- {
- cout<<i->first<<" ";
- }
- //rs.erase(i->first);
- }
- cout<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment