Codeforces Round 920 (Div. 3)----->D. Very Different Array

一,思路:这题是一道简单的贪心题目。只需要我们排完序之后用双指针来实现最大值的对映上最小值,取出差值最大的那个一对,指针移动。

二,代码:

#include <iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;

const int N=2e5+10;

typedef  long long ll;
typedef pair<int,int> pii;

ll arr[N],brr[N];

void Solved() {
   int n,m;
   cin>>n>>m;

   for(int i=1;i<=n;i++) cin>>arr[i];
   for(int i=1;i<=m;i++) cin>>brr[i];

   sort(arr+1,arr+1+n);
   sort(brr+1,brr+1+m);

   ll sum=0;

//定义四个指针分别对应两个数组排序后的首尾元素。
   int l=1,r=m,l1=1,r1=n;

   while(l1<=r1){

//比较出差值最大的那一对,指针移动
      if(brr[r]-arr[l1]>arr[r1]-brr[l]) sum+=abs(arr[l1++]-brr[r--]);
      else sum+=abs(arr[r1--]-brr[l++]);

   }

   cout<<sum<<endl;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int t;
    cin>>t;

    while(t--) {
        Solved();
    }
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值