补完以下C++程序,要求:算法实现数塔问题 #define N 10 class shuta {public: int maxADD[N][N],path[N][N],d[N][N]; public: shuta(); shuta(string Iujin); solve Max(); solve Min(); }
时间: 2023-06-19 19:10:00 浏览: 57
数塔问题的算法c++实现
#include <iostream>
#include <string>
#include <fstream>
#define N 10
using namespace std;
class shuta {
public:
int maxADD[N][N], path[N][N], d[N][N];
public:
shuta() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
maxADD[i][j] = 0;
path[i][j] = 0;
d[i][j] = 0;
}
}
}
shuta(string iujin) {
ifstream infile;
infile.open(iujin);
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= i; j++) {
infile >> d[i][j];
}
}
infile.close();
}
void solveMax() {
for (int j = 1; j <= N; j++) {
maxADD[N][j] = d[N][j];
}
for (int i = N - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (maxADD[i + 1][j] > maxADD[i + 1][j + 1]) {
maxADD[i][j] = maxADD[i + 1][j] + d[i][j];
path[i][j] = j;
} else {
maxADD[i][j] = maxADD[i + 1][j + 1] + d[i][j];
path[i][j] = j + 1;
}
}
}
cout << "最大和为:" << maxADD[1][1] << endl;
}
void solveMin() {
for (int j = 1; j <= N; j++) {
maxADD[N][j] = d[N][j];
}
for (int i = N - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (maxADD[i + 1][j] < maxADD[i + 1][j + 1]) {
maxADD[i][j] = maxADD[i + 1][j] + d[i][j];
path[i][j] = j;
} else {
maxADD[i][j] = maxADD[i + 1][j + 1] + d[i][j];
path[i][j] = j + 1;
}
}
}
cout << "最小和为:" << maxADD[1][1] << endl;
}
};
int main() {
shuta s("shuta.txt");
s.solveMax();
s.solveMin();
return 0;
}
阅读全文