将下面代码改为c++语言:import sys MAX = 20001 INF = 99999999 def init(): global n, T, Coins, m print("输入硬币种数:") n = int(input()) print("输入硬币面值以及此面值硬币个数:") T = [] Coins = [] for i in range(n): t, coins = map(int, input().split()) T.append(t) Coins.append(coins) print("输入要找的钱数:") m = int(input()) if __name__ == '__main__': init() c = [INF] * (m + 1) c[0] = 0 w = [0] * n for i in range(n): for j in range(1, Coins[i] + 1): for k in range(T[i], m + 1): c[k] = min(c[k], c[k - T[i]] + 1) if c[m] != INF: p = m while c[p]: for i in range(n): if p - T[i] >= 0 and c[p] == c[p - T[i]] + 1: w[i] += 1 p -= T[i] break print("最少硬币个数为:%d" % c[m]) for i in range(n): if w[i] != 0: print("面值为%d的硬币个数为:%d" % (T[i], w[i])) else: print("此题无解")
时间: 2024-02-14 18:13:03 浏览: 64
下面是将Python代码转换为C++的代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 20001;
const int INF = 99999999;
int n, m;
vector<int> T, Coins;
void init() {
cout << "输入硬币种数:" << endl;
cin >> n;
cout << "输入硬币面值以及此面值硬币个数:" << endl;
T.clear();
Coins.clear();
for (int i = 0; i < n; i++) {
int t, coins;
cin >> t >> coins;
T.push_back(t);
Coins.push_back(coins);
}
cout << "输入要找的钱数:" << endl;
cin >> m;
}
void solve() {
vector<int> c(m + 1, INF);
vector<int> w(n, 0);
c[0] = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j <= Coins[i]; j++) {
for (int k = T[i]; k <= m; k++) {
c[k] = min(c[k], c[k - T[i]] + 1);
}
}
}
if (c[m] != INF) {
int p = m;
while (c[p] > 0) { // 注意这里是大于0,不是不等于INF
for (int i = 0; i < n; i++) {
if (p - T[i] >= 0 && c[p] == c[p - T[i]] + 1) {
w[i]++;
p -= T[i];
break;
}
}
}
cout << "最少硬币个数为:" << c[m] << endl;
for (int i = 0; i < n; i++) {
if (w[i] != 0) {
cout << "面值为" << T[i] << "的硬币个数为:" << w[i] << endl;
}
}
} else {
cout << "此题无解" << endl;
}
}
int main() {
init();
solve();
return 0;
}
```
希望这个C++代码可以解决你的问题。
阅读全文