【动态规划】[luoguP2858 USACO06FEB]奶牛零食Treats for the Cows

来源:互联网 发布:java程序设计培训学校 编辑:程序博客网 时间:2024/05/22 01:40

题目
比较裸 比较简单的区间dp
我们每次都是从两头拿掉其中的一个 但是具体是哪一个 我们不知道 但我们知道的是一定是从两头拿
我们设f[i][j]为剩下没有拿的最左端是第i个 最右端是第j个 能出状态转移方程式

f[i][j]=max(f[i+1][j]+a[i](nj+i),f[i][j1]+a[j](nj+i))

i + 1就是取了最左边的 从而加上那件东西的价值 j - 1同理
至于n - j - i就是当前是拿到第几次了 这个有可能一下子想不出来吧

代码实现更新一个记忆化搜索的 没有了n - j - i而是直接用一个变量记录当前是第几次了 毕竟是DFS。。

代码如下

#include<iostream>#include<cstdio>#include<cctype>    using namespace std;    #define in = read();    typedef long long ll;    typedef unsigned int ui;    const ll size = 5000 + 100;        int n;        int ans;        int a[size];        int f[size][size];inline ll read(){        ll num = 0 , f = 1;    char ch = getchar();        while(!isdigit(ch)){                if(ch == '-')   f = -1;                ch = getchar();        }        while(isdigit(ch)){                num = num*10 + ch - '0';                ch = getchar();        }        return num*f;}ll dfs(ll x , ll y , ll z){        if(z == n + 1)      return 0;        if(f[x][y])     return f[x][y];        f[x][y] = max(dfs(x + 1 , y , z + 1) + a[x]*z , dfs(x , y - 1 , z + 1) + a[y]*z);        return f[x][y];}int main(){        n in;        for(register int i=1;i<=n;i++)                a[i] in;        printf("%d" , dfs(1 , n , 1));}//COYG
原创粉丝点击