hdu1231最大连续子序列

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1231

如果做题的时候没有看见K的范围,那么TLE经典代码如下: - -!

#include <cstdio>

const int Min = -1e9;

int a[10005];
int n;
int main()

{
    while(~scanf("%d",&n),n)
    {
        int cow,col;
        int ans = Min;
        int flag = 1;
        for(int i = 0;i < n;++i){
            scanf("%d",&a[i]);
            if(a[i] >= 0)
                flag = 0;
        }
        if(flag)
        {
            printf("0 %d %d\n",a[0],a[n - 1]);
            continue;
        }
        for(int i = 0;i < n;++i)
        {
            for(int j = i;j < n;++j)
            {
                int sum = 0;
                for(int k = i;k <= j;++k)
                {
                    sum += a[k];
                }
                if(ans < sum)
                {
                    ans = sum;
                    cow = i;
                    col = j;
                }
            }
        }
        printf("%d %d %d\n",ans,a[cow],a[col]);
    }
    return 0;
}

我又仔细的想了想,a[start] ~ a[end] 这个序列的和可以由a[start] ~ a[end - 1] + a[end] 得来,三层循环变成了两层循环,还是TLE,看来只有线性的了

TLE代码:
#include <cstdio>

const int Min = -1e9;

int a[10005];
int n;
int main()

{
    while(~scanf("%d",&n),n)
    {
        int cow,col;
        int ans = Min;
        int flag = 1;
        for(int i = 0;i < n;++i){
            scanf("%d",&a[i]);
            if(a[i] >= 0)
                flag = 0;
        }
        if(flag)
        {
            printf("0 %d %d\n",a[0],a[n - 1]);
            continue;
        }
        for(int i = 0;i < n;++i)
        {
            int sum = 0;
            for(int j = i;j < n;++j)
            {
                sum += a[j];
                if(sum > ans)
                {
                    ans = sum;
                    cow = i;
                    col = j;
                }
            }
        }
        printf("%d %d %d\n",ans,a[cow],a[col]);
    }
    return 0;
}


只有在想想线性的了。。

DP的思想。。。。

AC:
#include <cstdio>


int a[10005];
int n;
int main()

{
    while(~scanf("%d",&n),n)
    {
        int start,End,x,y;
        int flag = 1;
        for(int i = 0;i < n;++i){
            scanf("%d",&a[i]);
            if(a[i] >= 0)
                flag = 0;
        }
        if(flag)
        {
            printf("0 %d %d\n",a[0],a[n - 1]);
            continue;
        }
        int sum = a[0];
        int ans = a[0];
        start = End = x = y = 0 ;
        for(int i = 1;i < n;++i)
        {
            if(sum > 0)
            {
                sum += a[i];
                End = i;
            }
            if(sum <= 0)
            {
                sum = a[i];
                start = i;
                End = i;
            }
            if(sum > ans)
            {
                ans = sum;
                x = start;
                y = End;
            }
        }
        printf("%d %d %d\n",ans,a[x],a[y]);
    }
    return 0;
}


你可能感兴趣的:(dp,ACM)