2018寒假训练-动态规划

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;
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值