顺序表应用8:最大子段和之动态规划法

来源:互联网 发布:修改apache配置文件 编辑:程序博客网 时间:2024/06/02 22:54

Problem Description

 给定n(1<=n<=100000)个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n。 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。

 

注意:本题目要求用动态规划法求解,只需要输出最大子段和的值。

Input

第一行输入整数n(1<=n<=100000),表示整数序列中的数据元素个数;

第二行依次输入n个整数,对应顺序表中存放的每个数据元素值。

Output

输出所求的最大子段和

 

Example Input

6-2 11 -4 13 -5 -2

Example Output

20

#include <stdio.h>
#include <stdlib.h>
#define list_size 100000
#define OVERFLOW -1
#define OK 1
int count;
typedef int ElemType;
typedef struct
{
    ElemType *elem;
    int length;
    int listsize;
}Sqlist;
int max(int a, int b)
{
    if(a > b)
        return a;
    else
        return b;
}
int InitList(Sqlist &L)
{
    L.elem = (ElemType *)malloc(list_size * sizeof(ElemType));
    if( !L.elem) exit(OVERFLOW);
    L.length = 0;
    L.listsize = list_size;
    return OK;
}
void creatnewlist(Sqlist &L, int n)
{
    int i;
    for(i = 0; i < n; i++)
        scanf("%d", &L.elem[i]);
}
int maxsum(Sqlist &L, int n)
{
    int max = 0, sum = 0;
    for(int i = 0; i < n; i++)
    {
        sum += L.elem[i];
        if(sum < 0) sum = 0;
        else if(sum > max) max = sum;
    }
    return max;
}
int main()
{
    Sqlist L;
    int n, s;
    scanf("%d", &n);
    InitList(L);
    creatnewlist(L, n);
    s = maxsum(L, n);
    printf("%d\n", s);
    return 0;
}
链表:
有序链表的建立
#include <stdio.h>
#include <stdlib.h>
int k = 0, h = 0;
struct node
{
    int data;
    struct node *next;
};
struct node *creat(int n)
{
    struct node *head, *p, *tail;
    head = (struct node *)malloc(sizeof(struct node));
    head->next = NULL;
    tail = head;
    int i;
    for(i = 1; i <= n; i++)
    {
        p = (struct node *)malloc(sizeof(struct node));
        scanf("%d", &p->data);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    return head;
};
void sort(struct node *head)
{
    struct node *p, *q, *r;
    p = head->next;
    if(p != NULL)
    {
        r = p->next;
        p->next =  NULL;
        p = r;
        while(p != NULL)
        {
            r = p->next;
            q = head;
            while(q->next != NULL && q->next->data <= p->data)
                q = q->next;
            p->next = q->next;
            q->next = p;
            p = r;
        }
    }
}
void display(struct node *head)
{
    struct node *p;
    p = head->next;
    while(p != NULL)
    {
        if(p->next != NULL)
            printf("%d ", p->data);
        else
            printf("%d\n", p->data);
        p = p->next;
    }
}
int main()
{
    struct node *head;
    int n;
    scanf("%d", &n);
    head = creat(n);
    sort(head);
    display(head);
    return 0;
}