A1044 Shopping in Mars [连续子序列分割]

在这里插入图片描述
题目大意:给出一个数字序列和一个数s,在数字序列里求出所有和值为s的连续子序列。如果没有,就输出所有和值大于s的子序列里面和值最接近s的子序列。
解题思路:参考大神的,先遍历第一遍存值,利用和之差找出接近或者等于的值,然后再遍历一遍输出符合要求的相应位置。这题有点缺乏思考

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
int a[100001] = { 0 };
int main()
{
	int n, m;
	cin >> n >> m;
	int low = 0, inf = 9999999;
	bool notfound = true;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		a[i] += a[i - 1];
		while (a[i] - a[low] > m)
		{
			inf = min(inf, a[i] - a[low]);
			low++;
		}
		if (a[i] - a[low] == m)
		{
			cout << low + 1 << "-" << i << endl;
			notfound = false;
		}
	}
	if (notfound)
	{
		low = 0;
		for (int i = 1; i <= n; i++)
		{
			while (a[i] - a[low] > inf)
			{
				low++;
			}
			if (a[i] - a[low] == inf)
			{
				cout << low + 1 << "-" << i << endl;
			}
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Hsiung123/p/13812062.html