1921D - Very Different Array - CodeForces Solution


greedy

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

#define ios ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long
#define ull unsigned long long
#define inf INT_MAX
#define llinf LLONG_MAX
#define mt make_tuple
#define mp make_pair
#define parll pair<ll,ll>
#define parii pair<int,int>
#define frs first
#define sec second
#define neparno(x) (x&1)
#define parno(x) (!neparno(x))
#define lowbit(x) (x&-x)
#define nzd __gcd
#define nzs(e1,e2) ((e1*e2)/nzd(e1,e2))
#define yes cout << "Yes\n"
#define no cout << "No\n"
#define yesno(x) cout << ((x)?"Yes\n":"No\n")
#define condcout(x,y,z) cout << ((x)?y:z) << "\n"
#define all(V) V.begin(),V.end()
#define fill(V,v) fill(all(V),v)
#define l_b(BRL,brl) lower_bound( BRL.begin(), BRL.end(), brl )-BRL.begin()-1
#define u_b(BRU,bru) upper_bound( BRU.begin(), BRU.end(), bru )-BRU.begin()
#define mod 1000000007
#define mxn 200002

ll q,n,m,A[mxn],B[mxn];

int main()
{
    ios;

    cin >> q;
    while ( q-- )
    {
        cin >> n >> m;
        for ( ll i = 1; i <= n; i++ )
        {
            cin >> A[i];
        }
        for ( ll i = 1; i <= m; i++ )
        {
            cin >> B[i];
        }
        sort(A+1,A+n+1);
        sort(B+1,B+m+1);

        ll x = 0;
        for ( ll i = 1; i <= n; i++ )
        {
            x += abs(B[m-i+1]-A[i]);
        }

        ll rez = x;
        for ( ll i = 1; i <= n; i++ )
        {
            rez = max( rez, x=x-abs(A[n-i+1]-B[m-(n-i+1)+1])+abs(A[n-i+1]-B[i]) );
        }
        cout << rez << "\n";
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum
742A - Arpa’s hard exam and Mehrdad’s naive cheat
1492A - Three swimmers
1360E - Polygon
1517D - Explorer Space
1230B - Ania and Minimizing
1201A - Important Exam
676A - Nicholas and Permutation
431A - Black Square
474B - Worms
987B - High School Become Human
1223A - CME
1658B - Marin and Anti-coprime Permutation
14B - Young Photographer
143A - Help Vasilisa the Wise 2