1.动态规划入门题目:数字三角形(POJ1163)
The Triangle
| Time Limit: 1000MS | Memory Limit: 10000K | |
| Total Submissions: 30397 | Accepted: 17973 |
Description
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1) Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
Sample Output
30
翻译:在上面的数字三角形中寻找一条从顶部到底边的路径,使得路径上所经过的数字之和最大。路径上的每一步都只能往左下或 右下走。只需要求出这个最大和即可,不必给出具体路径。 三角形的行数大于1小于等于100,数字为 0 - 99。
#include<iostream>
using namespace std;
int a[105][105];
int b[105];
int n;
int main(){
cin>>n;
for(int i=0;i<n;i++)
for(int j=0;j<=i;j++)
cin>>a[i][j];
for(int i=0;i<n-1;i++)
b[i]=a[n-1][i];
for(int i=n-2;i>=0;i--){
for(int j=0;j<=i;j++)
b[j]=max(b[j],b[j+1])+a[i][j];
}
cout<<b[0]<<endl;
return 0;
}
2.动态规划案例:分糖果(题目1550)
时间限制:1 秒
内存限制:128 兆
特殊判题:否
题目描述:
给从左至右排好队的小朋友们分糖果,
要求:
1.每个小朋友都有一个得分,任意两个相邻的小朋友,得分较高的所得的糖果必须大于得分较低的,相等则不作要求。
2.每个小朋友至少获得一个糖果。
求,至少需要的糖果数。
输入:
输入包含多组测试数据,每组测试数据由一个整数n(1<=n<=100000)开头,接下去一行包含n个整数,代表每个小朋友的分数Si(1<=Si<=10000)。
输出:
对于每组测试数据,输出一个整数,代表至少需要的糖果数。
样例输入:
3
1 10 1
3
6 2 3
2
1 1
样例输出:
4
5
2
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll n,sum;
const ll maxn=100005;
int a[maxn],b[maxn];
int dp(int r){
if(b[r]>0)return b[r];
b[r]=1;
if(r+1<n&&a[r+1]<a[r])
b[r]=max(b[r],dp(r+1)+1);
if(r-1>=0&&a[r-1]<a[r])
b[r]=max(b[r],dp(r-1)+1);
return b[r];
}
int main(){
while(cin>>n){
memset(b,0,sizeof(b));
for(ll i=0;i<n;i++)
cin>>a[i];
sum=0;
for(int i=0;i<n;i++)
sum+=dp(i);
cout<<sum<<endl;
}
return 0;
}
本文解析了两道经典的动态规划题目:数字三角形问题和分糖果问题。通过代码示例详细介绍了如何使用动态规划求解从三角形顶点到底边的最大路径和,以及在满足特定条件下的最少糖果分配方案。

1716

被折叠的 条评论
为什么被折叠?



