个人作业十:返回子数组二

返回一个整数数组中最大子数组的和2

 

一、设计思路:

  由于我们第一个版本的算法不太好,导致后来拓展的两个程序无法很好地实现,我们就又重新设计了一个。我们是先写的首尾相连的那个程序,在它的基础上稍微修改了一下。

(1)数据结构是链表,存放数据和next指针;

(2)生成特别大的随机数,数据也设置得比较多。

二、源代码

// 最大子数组的和溢出.cpp : Defines the entry point for the console application.

// 袁佩佩 于海洋

#include "stdafx.h"

#include<iostream.h>

#include "stdlib.h"

#include<time.h>

#define NUM 1000

/*链表数据结构*/

typedef struct LNode

{

    int data;

    struct LNode *next;

}LNode,*LinkList;

/*链表的初始化*/

void InitList(LinkList &L)

{

    L=new LNode;

    L->next=NULL;

}

/*链表数据的插入*/

void InsertList(LinkList &L)

{

    LNode *head,*temp;

    head=L;

    srand(time(NULL));

    for(int i=0;i<NUM;i++)

    {

        temp=new LNode;

        temp->data=rand()%2000000000-10000;

       
temp->next=NULL;

        head->next=temp;

        head=head->next;

    }

}

void output(LinkList L)

{

    for(int i=0;i<NUM;i++)

    {

        cout<<L->next->data<<" ";

        L=L->next;

        if((i+1)%10==0)

        {

            cout<<endl;

        }

    }

}

int main(int argc, char* argv[])

{

    int max,sum,flag=0;                //sum是子数组的和,max是最大的子数组的和

    int ordern=0,orderx=0;

    LinkList L;

    LNode *temp1,*temp2;

    InitList(L);

    InsertList(L);                    //由用户往链表中插入数据

    temp2=L->next;

    max=L->next->data;                //max初值是链表中第一个数

    for(int j=0;j<NUM;j++,temp2=temp2->next)

    {

        for(int k=j;k<NUM;k++)

        {

            sum=0;

            temp1=temp2;

            for(int h=j;h<=k;h++,temp1=temp1->next)

            {

                 sum=sum+temp1->data;

            }

             if(max<sum)             //将最大值赋给max,并且保存当时的序号 

             {

                 max=sum;

                 ordern=j;

                 orderx=k;

             }

        }

    }

    if(sum==2147483647)

    {

        cout<<"数据溢出,程序出错!!!";

    }

    temp1=L->next;

    cout<<"数组:"<<endl;

    output(L);

    cout<<endl<<"最大子数组是:";

    for(int i=0;i<ordern;i++)         //找出取得最大值的时候的子数组的第一个数

    {

        temp1=temp1->next;

    }

    for(j=0;j<(orderx-ordern+1);j++,temp1=temp1->next)//将取得最大和的子数组元素输出

    {

        cout<<temp1->data<<"  ";

    }

    cout<<endl<<"最大子数组的和是:"<<max<<endl;;

    return 0;

}

三、运行结果

当代码中产生随机数的范围过大,编译器提示

                       

 

四、遇到的困难

  虽然这次的题目要求看起来没什么难度,但是事实证明与计算机底层相接的部分才是难点啊。用软件解决硬件问题让我们头疼了很久,我们曾经有两次以为自己调出 来了,但是继续把数值增大后,结果就不正确了。我们就另外写了个小程序来观察int32 类型的边界值有多大,然后我们发现最大值是232-1,再加一,就会变成-232。我们就设置了相应的判断条件,使最大值溢出时提示出错。

原文地址:https://www.cnblogs.com/lrhan/p/5609612.html