zoukankan      html  css  js  c++  java
  • MAX SUM

    先粘题目

    Max Sum

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 167166    Accepted Submission(s): 39004


    Problem Description
    Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
     
    Input
    The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
     
    Output
    For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
     
    Sample Input
    2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
     
    Sample Output
    Case 1: 14 1 4 Case 2: 7 1 6
     
     
    很明显是最长子序列问题。一开始我也是就这么写的。但是处理起来又貌似有点不一样。数组太大。总是Runtime Error (ACCESS_VIOLATION)。我于是百度了一下。借鉴别人借鉴的别人的。
     
    http://blog.csdn.net/akof1314/article/details/4757021
     
     
    自己Ac代码:
    #include<stdio.h>
    #include<iostream>
    #include<algorithm>
    #include<climits>

    using namespace std;

    #define N 11000

    int a[N];

    int main()
    {
        int t, i, k, n, max, x, temp, p1, p2, now;

        scanf("%d", &t);

        for(k = 1; k <= t; k++)
        {
            scanf("%d%d", &n, &temp);
            
            x = p1 = p2 = 1;
            max  = now = temp;//初始化
            
            for(i = 2; i <= n; i++)
            {
                scanf("%d", &temp);

                if(now+temp < temp)//判断这个数前边的数是加还是不加,如果不加就把起始位置置为i
                {
                    now = temp;
                    x = i;
                }
                else now += temp;

                if(now > max)//记录当前最大值时的起始及结束位置坐标
                {
                    p1 = x;
                    p2 = i;
                    max = now;
                }
            }


            if(k != 1)
                printf(" ");//格式控制,也可以由k是否等于n判断输出之后是否输出换行
            printf("Case %d: ", k);
            printf("%d %d %d ", max, p1, p2);
        }
        return 0;
    }

    IDEAS:
    计算机,或者程序自身是有记忆功能的。当你处理每一步时,你都可以利用前边已经计算过的值或者结果处理你下一步如何操作。尤其是当数组很大,或者时间超限的时候。既可以减少运行内存还能降低运行时间。。你当然也可以选择继续没想法下去
    让未来到来 让过去过去
  • 相关阅读:
    Date日期对象
    JAVA适配器
    java 对象的多态性
    简单轮播
    ecshop 教程地址
    瀑布流js排列
    phpcms 搜索结果页面栏目不显示解决 方法
    手机自动跳转
    字串符转换数字、取小数点后两位数的方法
    js 判断鼠标进去方向
  • 原文地址:https://www.cnblogs.com/Tinamei/p/4447088.html
Copyright © 2011-2022 走看看