问题描述
Given a sequence 1,2,3,…N, your job is to calculate all the possible sub-sequences that the sum of the sub-sequence is M.
输入
Input contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.
输出
For each test case, print all the possible sub-sequence that its sum is M.The format is show in the sample below.print a blank line after each test case.
代码
-
这道题目的大致要求是:
- 输出对于M来说,从1到N中,连续的数组,是否和刚好是M的,如果是立即输出,格式为[X,X]
最初的想法是暴力求解,遍历一遍之后肯定能够找出最终解,但是由于数据规模是 <= 1000000000
,会超时;因此考虑换一种方式,借助等差数列求和公式进行简化,借助的文章是HOJ 2058 The sum problem.大家可以直接看这篇文章,觉得麻烦的话我也会给大家将公式截图展示.如下
这是等差求和公式(注意不要看错,是从a1开始计算求和),再将公式整合一下可以得到
-
那么现在就可以放心的编写代码的公式part了;
-
首先由公式可以知道最大长度只能取到
m
∗
2
\sqrt {m*2}
m∗2,缩短长度的寻找范围;
其次就是对长度进行遍历,利用公式所示的关系,进行判断是否是正解
#include <iostream>
using namespace std;
int main() {
int n, m;
int i, maxlen, t;
while (cin >> n >> m) {
if ((n == 0) && (m == 0)) break;
maxlen = sqrt(m * 2);
for (i = maxlen; i > 0; i--) {//i表示序列长度
t = m - i * (i - 1) / 2;
if (t % i == 0) cout << "[" << t / i << "," << t / i + i - 1 << "]" << endl;
}
cout << endl;
}
return 0;
}
最后,大家加油 ! 欢迎大家交流讨论.