码迷,mamicode.com
首页 > 编程语言 > 详细

结对开发Ⅳ——一维数组求和最大的子数组(大数溢出)

时间:2015-03-29 00:26:13      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

一、设计思路

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

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

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

二、源代码

未调试好

 1 // 一维最大子数组2.cpp : Defines the entry point for the console application.
 2 // 袁佩佩 于海洋
 3 
 4 #include "stdafx.h"
 5 #include<iostream.h>
 6 #include "stdlib.h"
 7 #define NUM 100
 8 
 9 /*链表数据结构*/
10 typedef struct LNode
11 {
12     int data;
13     struct LNode *next;
14 }LNode,*LinkList;
15 /*链表的初始化*/
16 void InitList(LinkList &L)
17 {
18     L=new LNode;
19     L->next=NULL;
20 }
21 /*链表数据的插入*/
22 void InsertList(LinkList &L)//建立循环链表
23 {
24     LNode *head,*temp;
25     head=L;
26     for(int i=0;i<NUM;i++)
27     {
28         temp=new LNode;
29         temp->data=rand()%2000000000+1000000000;
30         temp->next=NULL;
31         head->next=temp;
32         head=head->next;
33     }
34 }
35 void output(LinkList L)
36 {
37     for(int i=0;i<NUM;i++)
38     {
39         cout<<L->next->data<<" ";
40         L=L->next;
41     }
42 }
43 int main(int argc, char* argv[])
44 {
45     int max,sum,flag=0;                //sum是字数组的和,max是最大的子数组的和
46     int ordern=0,orderx=0;
47     LinkList L;
48     LNode *temp1,*temp2;
49     InitList(L);
50     InsertList(L);                    //由用户往链表中插入数据
51     temp2=L->next;
52     max=L->next->data;                //max初值是链表中第一个数
53     for(int j=0;j<NUM;j++,temp2=temp2->next)
54     {
55         for(int k=j;k<NUM;k++)
56         {
57             sum=0;
58             temp1=temp2;
59             for(int h=j;h<=k;h++,temp1=temp1->next)
60             {
61                  sum=sum+temp1->data;
62             }
63              if(max<sum)             //将最大值赋给max,并且保存当时的序号 
64              {
65                  max=sum;
66                  ordern=j;
67                  orderx=k;
68              }
69         }
70     }
71     temp1=L->next;
72     cout<<"数组:"<<endl;
73     output(L);
74     cout<<endl<<"最大子数组是:";
75     for(int i=0;i<ordern;i++)         //找出取得最大值的时候的子数组的第一个数
76     {
77         temp1=temp1->next;
78     }
79     for(j=0;j<(orderx-ordern+1);j++,temp1=temp1->next)//将取得最大和的子数组元素输出
80     {
81         cout<<temp1->data<<"  ";
82     }
83     cout<<endl<<"最大子数组的和是:"<<max<<endl;;
84 
85     return 0;
86 }

 

三、运行截图

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

技术分享

 

 

四、心得体会

五、无图无真相

结对开发Ⅳ——一维数组求和最大的子数组(大数溢出)

标签:

原文地址:http://www.cnblogs.com/JJJanepp/p/4375025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!