动态规划总结

来源:互联网 发布:tf卡写入数据错误 编辑:程序博客网 时间:2024/05/19 14:53

1.斐波那契数列的动规写法(避免递归树重复计算)

<pre name="code" class="cpp">#include <functional>#include <algorithm>#include <iostream>#include <fstream>#include <sstream>#include <iomanip>#include <numeric>#include <cstring>#include <climits>#include <cassert>#include <complex>#include <cstdio>#include <string>#include <vector>#include <bitset>#include <queue>#include <stack>#include <cmath>#include <ctime>#include <list>#include <set>#include <map>using namespace std;#pragma comment(linker, "/STACK:102400000,102400000")typedef long long LL;typedef double DB;typedef unsigned uint;typedef unsigned long long uLL;/** Constant List .. **/ //{const int MOD = int(1e9)+7;const int INF = 0x3f3f3f3f;const LL INFF = 0x3f3f3f3f3f3f3f3fLL;const DB EPS = 1e-9;const DB OO = 1e20;const DB PI = acos(-1.0); //M_PI;const int maxn = 100001;int f[maxn];int n;int fib(int n){    if(f[n] != 0)        return f[n];    if(n == 0)        return 0;    else if(n == 1)        return 1;    else    {        f[n] = fib(n-1) + fib(n-2);        return f[n];    }}int main(){    #ifdef DoubleQ    freopen("in.txt" , "r" , stdin);    #endif;    while(~scanf("%d",&n))    {        memset(f , 0  , sizeof(f));        cout << fib(n) << endl;    }}



2.N层数字三角形求最小和

d[ x ] [ y ] = min(d[x + 1 ]  [ y ]  ,  d[x + 1 ] [ y + 1 ]) + a[ x ] [ y ] (节省时间保存中间路径) d[ x ] [ y ] = min( vis[ x+1] [ y ]  , vis[ x+1 ] [ y+1 ]) + a[ x ] [ y ];

#include <functional>#include <algorithm>#include <iostream>#include <fstream>#include <sstream>#include <iomanip>#include <numeric>#include <cstring>#include <climits>#include <cassert>#include <complex>#include <cstdio>#include <string>#include <vector>#include <bitset>#include <queue>#include <stack>#include <cmath>#include <ctime>#include <list>#include <set>#include <map>using namespace std;#pragma comment(linker, "/STACK:102400000,102400000")typedef long long LL;typedef double DB;typedef unsigned uint;typedef unsigned long long uLL;/** Constant List .. **/ //{const int MOD = int(1e9)+7;const int INF = 0x3f3f3f3f;const LL INFF = 0x3f3f3f3f3f3f3f3fLL;const DB EPS = 1e-9;const DB OO = 1e20;const DB PI = acos(-1.0); //M_PI;using namespace std;int d[1111][1111];int vis[1111][1111];int n;int f(int x , int y){    if(x == n)        return d[x][y];    if(vis[x+1][y] == 0)        vis[x+1][y] = f(x+1 , y);    if(vis[x+1][y+1] == 0)        vis[x+1][y+1] = f(x+1 , y+1);    return max(vis[x+1][y] , vis[x+1][y+1]) + d[x][y];}int main(){    #ifdef DoubleQ    freopen("in.txt" , "r" , stdin);    #endif;    while(~scanf("%d",&n))    {        memset(vis , 0  , sizeof(vis));        for(int i = 1 ; i <= n ; i++)        {            for(int j = 1 ;  j <= i ; j ++)            {                cin >> d[i][j];            }        }        cout << f(1,1) << endl;    }}


0 0