• CF 1899C 学习笔记


    C. Yarik and Array

    time limit per test

    1 second

    memory limit per test

    256 megabytes

    input

    standard input

    output

    standard output

    A subarray is a continuous part of array.

    Yarik recently found an array 𝑎� of 𝑛� elements and became very interested in finding the maximum sum of a non empty subarray. However, Yarik doesn't like consecutive integers with the same parity, so the subarray he chooses must have alternating parities for adjacent elements.

    For example, [1,2,3][1,2,3] is acceptable, but [1,2,4][1,2,4] is not, as 22 and 44 are both even and adjacent.

    You need to help Yarik by finding the maximum sum of such a subarray.

    Input

    The first line contains an integer 𝑡� (1≤𝑡≤104)(1≤�≤104) — number of test cases. Each test case is described as follows.

    The first line of each test case contains an integer 𝑛� (1≤𝑛≤2⋅105)(1≤�≤2⋅105) — length of the array.

    The second line of each test case contains 𝑛� integers 𝑎1,𝑎2,…,𝑎𝑛�1,�2,…,�� (−103≤𝑎𝑖≤103)(−103≤��≤103) — elements of the array.

    It is guaranteed that the sum of 𝑛� for all test cases does not exceed 2⋅1052⋅105.

    Output

    For each test case, output a single integer — the answer to the problem.

    Example

    input

    Copy

     
    

    7

    5

    1 2 3 4 5

    4

    9 9 8 8

    6

    -1 4 -1 0 5 -4

    4

    -1 2 4 -3

    1

    -1000

    3

    101 -99 101

    20

    -10 5 -8 10 6 -10 7 9 -2 -6 7 2 -4 6 -1 7 -6 -7 4 1

    output

    Copy

    15
    17
    8
    4
    -1000
    101
    10
    1. #include
    2. using namespace std;
    3. const int N=2e5+10;
    4. int a[N],f[N];
    5. int main()
    6. {
    7. int t;
    8. scanf("%d",&t);
    9. while(t--)
    10. {
    11. int n;
    12. scanf("%d",&n);
    13. for(int i=1;i<=n;i++)
    14. {
    15. scanf("%d",&a[i]);
    16. f[i]=a[i];
    17. }
    18. for(int i=n-1;i>=1;i--)
    19. {
    20. if(abs(a[i]%2)!=abs(a[i+1]%2))
    21. {
    22. f[i]=max(f[i],f[i]+f[i+1]);
    23. }
    24. }
    25. int ans=-2e9;
    26. for(int i=1;i<=n;i++)
    27. {
    28. ans=max(ans,f[i]);
    29. }
    30. printf("%d\n",ans);
    31. }
    32. return 0;
    33. }

    赛时没有写出来,题目读懂了,但是写不出,该题属于一道动态规划的题目。

    题目的意思是:输入一个数组,求这个数组的一段连续序列,要求这段连续序列尽可能长,总和尽可能大,相邻两个元素奇偶性不同 。

    a数组用来存储数组元素,f数组用来存储某一段连续序列的和。输入所有数组元素的同时,初始化f数组,使得f数组最开始和a数组相同

    从最后一个元素开始处理,建立状态转移方程,进行奇偶性校验,如果相邻元素奇偶性不同,更新f数组,决定是否要把后面一段元素加上,从后面处理到前面,处理前面的元素的时候,后面的元素已经完成了预处理,所以可以解决这个问题

    最后面遍历f数组,找到f数组里面的最大值,即我们寻找的答案,输出即可

    参考题解:

    1.题解1

    2.cf官方题解

  • 相关阅读:
    poi3.10 excel xls 设置列宽行高背景色加粗
    将神经网络粒子化的内在合理性
    警惕!又2本期刊被“On Hold”!
    SpringBoot整合Junit
    Dockerfile
    vue(十二)——vue3新特性之Teleport
    推荐算法在商城系统实践
    QT图形视图框架绘制曲线图和Smith图
    浅谈GPT在数据库重构项目中的创新应用
    基于stm32单片机农业智能温室大棚温湿度光照测量报警系统Proteus仿真
  • 原文地址:https://blog.csdn.net/L3102250566/article/details/134486926