এই টিউটোরিয়ালে, আমরা এমন একটি প্রোগ্রাম নিয়ে আলোচনা করব যাতে একটি সংখ্যা N দৈর্ঘ্যকে রূপান্তরিত করা যায় যাতে এটিতে অন্তত 'K' বার যে কোনো একটি সংখ্যা থাকে।
এর জন্য আমাদেরকে প্রদত্ত দৈর্ঘ্যের N সংখ্যা দেওয়া হবে। আমাদের কাজ হল প্রদত্ত সংখ্যার সংখ্যাগুলিকে এমনভাবে রূপান্তর করা যাতে যেকোনো একটি সংখ্যা কমপক্ষে 'K' বার পুনরাবৃত্তি হয়। এছাড়াও, আপনাকে এই অপারেশনের খরচ গণনা করতে হবে যা উভয়ের মধ্যে নিখুঁত পার্থক্য এবং অবশেষে সর্বনিম্ন খরচ প্রিন্ট করতে হবে।
উদাহরণ
#include <bits/stdc++.h>
using namespace std;
//calculating the minimum value and final number
int get_final(int n, int k, string a){
int modtemp;
//count of numbers changed to k
int co;
string temp;
//storing the minimum cost
pair<int, string> ans = make_pair(INT_MAX, "");
for (int i = 0; i < 10; i++) {
temp = a;
//storing the temporary modified number
modtemp = 0;
co = count(a.begin(), a.end(), i + '0');
for (int j = 1; j < 10; j++) {
if (i + j < 10) {
for (int p = 0; p < n; p++) {
if (co <= k)
break;
if (i + '0' == temp[p] - j) {
temp[p] = i + '0';
modtemp += j;
co++;
}
}
}
if (i - j >= 0) {
for (int p = n - 1; p >= 0; p--) {
if (co >= k)
break;
if (i + '0' == temp[p] + j) {
temp[p] = i + '0';
modtemp += j;
co++;
}
}
}
}
//replacing the minimum cost with the previous one
ans = min(ans, make_pair(modtemp, temp));
}
cout << ans.first << endl << ans.second << endl;
}
int main(){
int n = 5, k = 4;
string a = "21122";
get_final(n, k, a);
return 0;
} আউটপুট
1 21222