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
is .
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 long, long long> a,pair<long long, long long> b){if (a.second == b.second)return a.first < b.first;return a.second > b.second;}void descendingWeights(long long n,long long k, long long a[]){vector<pair<long long, long long>> v;for (long long i = 0; i < n; i++){v.push_back({a[i], a[i] % k});}sort(v.begin(), v.end(), cmp);for (long long i = 0; i < v.size(); i++){cout << v[i].first << " ";}cout << "\n";}int main(){long long n = 5, k = 2;long long a[n] = {1, 2, 3, 4, 5};descendingWeights(n, k, a);return 0;}
No comments:
Post a Comment