轉換長度為 N 的數字,使其在 C++ 中至少包含一個數字“K”次
在本教程中,我們將討論一個程式,以轉換長度為 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP