zoukankan      html  css  js  c++  java
  • 刷题向》DP》关于基础DP(easy)

    openjudge  8464

    这道题其实很简单,算是DP的基础题,比较适合开拓DP思维。

    题目比较有欺骗性,其实稍微想想就可以解决,因为题意说第一次卖出后才能买入,所以我们可以考虑枚举断点,所以题目一下变得简单,我们线性扫两遍,算最大值就好了。

    具体为:

    由于不能同时进行两次交易,所以枚举断点,一遍扫做1到n的前n个的最大值,由于最大值一定是单调递增的,所以每次读入新的a[i],判断是否有更优解就好了,同理,一遍扫n到1的后n个的最大值,做同样的事,然后枚举断点取最大值。

    代码如下:

     1 #include<stdio.h>
     2 int T,n,a[100100],f[100100],g[100100],ans;
     3 int main()
     4 {
     5     scanf("%d",&T);
     6     while(T--)
     7     {
     8         int best=-2147483647,temp=2147483647;
     9         scanf("%d",&n);
    10         for(int i=1;i<=n;i++)
    11             scanf("%d",&a[i]);
    12         for(int i=1;i<=n;i++)
    13         {
    14             if(a[i]<temp)
    15                 temp=a[i];
    16             if(a[i]-temp>best)
    17                 best=a[i]-temp;
    18             f[i]=best;
    19         }
    20         best=-2147483647,temp=-2147483647;
    21         for(int i=n;i>=1;i--)
    22         {
    23             if(a[i]>temp)
    24                 temp=a[i];
    25             if(temp-a[i]>best)
    26             best=temp-a[i];
    27             g[i]=best;
    28         }
    29         for(int i=1;i<=n;i++)
    30             if(f[i]+g[i]>ans)ans=f[i]+g[i];
    31         printf("%d
    ",ans);
    32         ans=0;
    33     }
    34     return 0;
    35 }
    View Code
  • 相关阅读:
    POJ 3268 Silver Cow Party (Dijkstra)
    怒学三算法 POJ 2387 Til the Cows Come Home (Bellman_Ford || Dijkstra || SPFA)
    CF Amr and Music (贪心)
    CF Amr and Pins (数学)
    POJ 3253 Fence Repair (贪心)
    POJ 3069 Saruman's Army(贪心)
    POJ 3617 Best Cow Line (贪心)
    CF Anya and Ghosts (贪心)
    CF Fox And Names (拓扑排序)
    mysql8.0的新特性
  • 原文地址:https://www.cnblogs.com/PencilWang/p/5037267.html
Copyright © 2011-2022 走看看