zoukankan      html  css  js  c++  java
  • 求一个数组的最大子数组之和02

    这次程序代码在此基础上增加了首位相连形成环链

    1.用户输入环链长度,并输入每个环链数组

    2.根据算法将首位相连形成环链

    3.将子数组之和相加存入SUM

    4.输出SUM与子数组

    #include<iostream>
    using namespace std;
    void main()
    {
        int i;
        int s = 0, sum = 0, head = 0, end = 0, h = 0, e = 0, x = 0;
        cout << "请输入数组长度:";
        cin >> x;
        int a[100];
        cout << "请输入数组中的数:";
        for (i = 0; i<x; i++)
        {
            cin >> a[i];
        }
    
    
        for (i = 0; i<x; i++)        //子数组相加得到最大值
        {
            s += a[i];
            if (s>0)
            {
                e++;
            }
            else
            {
                s = 0;
                h = i + 1;
                e++;
            }
            if (s>sum)
            {
                sum = s;
                head = h;
                end = e;
            }
        }
        if (s > 0)            //环链首位相加时的情况
        {
            head = h;
            i = 0;
            e = e - x;
            while (s > 0 && e != h - 1)
            {
                s += a[i];
                i++;
                e++;
                if (s > sum)
                {
                    sum = s;
                    end = e;
                }
    
            }
    

          if (end > head)
          {
            sum = sum / 2;
          }
          cout << "最大子数组的和为:" << sum << endl;
          cout << "最大子数组为:";

         if (end > head)                //输出子数组
            {
                for (i = head; i < end; i++)
                {
                    cout << a[i];
                    cout << "   ";
                }
            }
            else
            {
                for (i = head; i < x; i++)
                {
                    cout << a[i];
                    cout << "   ";
                }
                for (i = 0; i < end; i++)
                {
                    cout << a[i];
                    cout << "   ";
                }
            }
        }
        system("pause");
    }

    合作人:靳琪

  • 相关阅读:
    Servlet的生命周期
    HTTP协议简单记录
    Tomcat和JavaWeb目录和流程
    02 html 表格表单
    01 初识HTML
    Python 利用pywin32批量将doc转换成docx再读取成一行存入excel
    power bi 数据红绿灯详细用法
    Linux和Windows启动后台程序
    MySQL导出数据字典
    适用于渗透测试不同阶段的工具收集整理
  • 原文地址:https://www.cnblogs.com/zjy666/p/5325781.html
Copyright © 2011-2022 走看看