我被困在从文本文件中读取二维数组中,但我做不到。我有您在代码中看到的 tri[][] 数组数据。我需要从文本中读取它,而不是在程序中定义。然后我将这些数据插入到程序中。
代码:
// C++ program for Dynamic
// Programming implementation of
// Max sum problem in a triangle
#include<bits/stdc++.h>
using namespace std;
#define N 4
int sumRec[N];
bool checkPrimeNumber(int n)
{
//cout << n;
bool flag = true;
for(int a = 2; a <= n/2; ++a)
{
if(n%a == 0)
{
flag = false;
}
}
//if number is 1 return false. 1 is not prime
if(n == 1)
flag = false;
return flag;
}
int maxPathSum(int tri[][N], int row, int col, int sum)
{
bool isPrime = checkPrimeNumber(tri[row][col]);
if(isPrime == true){
//Do nothing..
}
else if(row + 1 >= N){
sum = sum + tri[row][col];
if(sumRec[col]<sum)
sumRec[col]= sum;
}
else{
sum = sum + tri[row][col];
maxPathSum(tri, row + 1, col, sum);
maxPathSum(tri, row + 1, col + 1, sum);
}
}
int main()
{
int maxSum = 0;
int tri[N][N] = { {1, 0, 0, 0},
{8, 4, 0, 0},
{2, 6, 9, 0},
{8, 5, 9, 3}};
maxPathSum(tri, 0, 0, 0);
for (int i=0; i < N ; i++)
{
if(sumRec[i] >= maxSum)
maxSum = sumRec[i];
}
cout << maxSum;
return 0;
}