Descending Weights

You have been given an array A of size N and an integer K. Each element in this array is said to have a Special Weight. The special weight of an element 

a[i] is a[i]%K.

You now need to sort this array in Non-Increasing order of the weight of each element, i.e the element with the highest weight should appear first, then the element with the second highest weight, and so on. In case two elements have the same weight, the one with the lower value should appear in the output first.

Example:

Input:  n = 5, k = 2, a = [1,2,3,4,5]
Output: 1 3 5 2 4

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool cmp(pair<long longlong longa,
         pair<long longlong longb)
{
    if (a.second == b.second)
        return a.first < b.first;
    return a.second > b.second;
}

void descendingWeights(long long n,
                       long long klong long a[])
{
    vector<pair<long longlong long>> v;
    for (long long i = 0i < ni++)
    {

        v.push_back({a[i], a[i] % k});
    }
    sort(v.begin(), v.end(), cmp);
    for (long long i = 0i < v.size(); i++)
    {
        cout << v[i].first << " ";
    }
    cout << "\n";
}
int main()
{
    long long n = 5k = 2;

    long long a[n] = {12345};

    descendingWeights(nka);

    return 0;
}


No comments:

Post a Comment