Ryan has a keen interest in collecting gems. He always urged his father to let him collect more gems. So, on his birthday, his father offered him a surprise gift. The gift is described as follows.
Ryan is given a collection of N number of gems. Each gem is of a unique type and is assigned a unique number Ni (unique identity). Each gem has a weight associated with it (may or may not be unique). Ryan has a bag, with the capacity to hold gems up to weight K grams. The bag can hold gems up to a weight less than or equal to K grams.
He will use this bag to collect gems. Now, due to his keen interest in maintaining a collection of gems, he wants to collect as many distinct types of gems as possible. Now, he wants your help in selecting the maximum distinct types of gems for his collection. Based on the given conditions, output those distinct gems that will be collected in the given bag.
Example:
Input: n = 3, k = 6, v={{1,1},{2,2},{3,3}}
Output: 1->2->4->5->NULL
Approach
C++
#include <bits/stdc++.h>using namespace std;//comparator used for sortingbool 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 maximimeIt(long long n, long long k,vector<pair<long long, long long>> &v){sort(v.begin(), v.end(), cmp);set<long long> st;vector<long long> v1;for (long long i = 0; i < n; i++){long long len = st.size();st.insert(v[i].first);if (len != st.size()){k = k - v[i].second;if (k < 0){break;}elsev1.push_back(v[i].first);}}if (v1.size() == 0)cout << -1 << "\n";else{sort(v1.begin(), v1.end());for (long long i = 0; i < v1.size() - 1; i++)cout << v1[i] << ",";cout << v1[v1.size() - 1];}}int main(){long long n = 3, k = 6;vector<pair<long long, long long>> v = {{1, 1}, {2, 2},{3, 3}};maximimeIt(n, k, v);return 0;}
No comments:
Post a Comment