USACO Section 1.5 Number Triangles

/*
ID: lucien23
PROG: numtri
LANG: C++
*/

#include<iostream>
#include<fstream>
#include<vector>
#include<cmath>
using namespace std;

int main()
{
	ifstream infile("numtri.in");
	ofstream outfile("numtri.out");
	if(!infile || !outfile)
	{
		cout<<"file operation failure!"<<endl;
		return -1;
	}
	
	int R;
	infile>>R;
	vector<int*> nums,sums;
	
	for (int i=1;i<=R;i++)
	{
		int *pNum=new int[i];
		int *pSum=new int[i];
		for (int j=0;j<i;j++)
		{
			infile>>pNum[j];
			if(i==R)
				pSum[j]=pNum[j];
		}
		nums.push_back(pNum);
		sums.push_back(pSum);
	}

	/************************************************************************/
	/* 从下往上依次计算三角形中各个元素位置的最优解                                */
	/************************************************************************/
	for (int i=R-2;i>=0;i--)
	{
		for (int j=0;j<i+1;j++)
		{
			sums[i][j]=max(sums[i+1][j],sums[i+1][j+1])+nums[i][j];//动态规划思想
		}
	}
	outfile<<sums[0][0]<<endl;
	for (int i=0;i<R;i++)
	{
		delete[] nums[i];
	}

	return 0;
}

你可能感兴趣的:(Algorithm,C++,动态规划,USACO)