您的位置:首页 > 其它

最大子数组的和(溢出)

2015-03-30 12:29 169 查看
结对成员:于海洋 袁佩佩

一.题目及要求

题目: 返回一个整数数组中最大子数组的和。

要求: 要求程序必须能处理1000 个元素;

    每个元素是int32 类型的;

    输入一个整形数组,数组里有正数也有负数。

    数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

    求所有子数组的和的最大值。要求时间复杂度为O(n)。

二.源代码

// 最大子数组的和溢出.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;
}


三.结果及截图



















四.体会

  在两个int型的数相加时,如果大于2^31-1,那么就变为-2^31开始往上加,当再次达到2^31-1时,又变为-2^31,如此循环往上加,直至结束。

  在遇到问题的时候,找人商量,是比较好的,就算两个人都不会,但是商量商量着灵感就来了。

五.合作照

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: