3 Matching Arrays
n的范围有2e5,暴力找肯定不行。将这题时间复杂度打下来的关键在于贪心
贪心的点在于局部最优,尽可能的将b里相对大的分给a里相对小的,一共分k个这样的。最后再检查一下,如果不满足就是-1
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
int a[N],b[N];
struct node1{
int x,id;
}p[N];
struct node2{
int x,id;
}q[N];
bool cmp(struct node1 a,struct node1 b){
return a.x>b.x;
}
bool cmp2(struct node2 a,struct node2 b){
return a.x>b.x;
}
void solve(){
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++){
cin>>a[i];
p[i].x=a[i];
p[i].id=i;
}
for(int i=1;i<=n;i++){
cin>>b[i];
q[i].x=b[i];
q[i].id=i;
}
sort(p+1,p+1+n,cmp);
sort(q+1,q+1+n,cmp2);
vector<int>d(n+1);
for(int i=1;i<=k;i++){
int x=a[p[i].id];
int y=b[q[n+i-k].id];
if(x<=y){
cout<<"NO\n";
return;
}
d[p[i].id]=y;
}
for(int i=k+1;i<=n;i++){
if(a[p[i].id]>b[q[i-k].id]){
cout<<"NO\n";
return;
}
d[p[i].id]=b[q[i-k].id];
}
cout<<"YES\n";
for(int i=1;i<=n;i++){
cout<<d[i]<<" ";
}
cout<<"\n";
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t=1;
cin>>t;
for(int i=1;i<=t;i++)solve();
return 0;
}