这次程序代码在此基础上增加了首位相连形成环链
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"); }
合作人:靳琪