本帖最后由 gonff 于 2020-11-21 13:03 编辑
试着写了一下代码。没有加入输入部分,只是初始化了一下。你可以把数组改一改,如果满足要求,就自己再加入一些语句修饰一下。#include <stdio.h>
//用指针比较方便返回数组
int * find(int n, int S, int a[]) {
//初始化盒子参量
int begin = 0;
int end = 0;
int sum = a[0];
int destination[3] = { 0, 0, 0 };//最终返回的数组:第一二分量是盒子的开头和结尾,第三分量标记是否溢出。
//开始吞入:
for (; sum < S;) {
if (end < n-1) {
end++;
sum += a[end];
}
else { destination[2] = -1; break; };
};
//printf("吞入完成后end=%d\n", end);
//开始排出;
for (; sum >= S; begin++) {
if (sum - a[begin] >= S) {
destination[0] = begin+1;
destination[1] = end;
sum -= a[begin];
//printf("排出一次begin=%d\n", begin);
}
else { break; };
};
//printf("本次排出后begin=%d\tend=%d\n", begin,end);
//开始移动判断的循环
for (; end < n-1;) {
sum = sum + a[end + 1] - a[begin];
end++;
begin++;
//printf("移动结果end=%d", end);
if (a[end] > a[begin - 1]) {
for (; sum >= S; begin++) {
if ((sum - a[begin]) >= S) {
destination[0] = begin+1;
destination[1] = end;
sum -= a[begin];
//printf("排出一次begin=%d\n", begin);
}
else { break; };
};
};
};
return destination;
}
void main() {
//初始化数据
int n = 9;
int S = 15;
int a[] = { 1, 1, 3, 5, 10, 13, 19, 19, 5};
int sizea;
sizea = sizeof(a) / sizeof(int);
if (n != sizea) {
printf("尺寸不对,已改正n=%d\n", sizea);
n = sizea;
};
//指针用于返回数组
int *p;
p = find(n, S, a);
if (*(p+2) == -1) {
printf("%d\n", 0); printf("%d\n", 0);
}
else {
int destination[2] = { 0, 0 };
destination[0] = *p;
destination[1] = *(p + 1);
//printf("destination[0]=%d\n", destination[0]);
//printf("destination[1]=%d\n", destination[1]);
int len;
len = destination[1] - destination[0] + 1;
//打印结果
int i = 0;
printf("%d\n", len);
if (len > 1) {
for (; i < len - 1; i++) {
printf("%d", a[destination[0] + i]);
};
}
else { printf("%d", a[destination[0]]); };
};
}
|