-
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
-
输入有多组数据。
每组数据仅包括1个整数S(S<=1,000,000)。如果S为负数时,则结束输入。
-
对应每组数据,若不存在和为S的连续正数序列,则输出“Pity!”;否则,按照开始数字从小到大的顺序,输出所有和为S的连续正数序列。每组数据末尾以“#”号结束。
-
4 5 100 -1
-
Pity! # 2 3 # 9 10 11 12 13 14 15 16 18 19 20 21 22 #
首位指向探查法,两个下标变化复杂度是O(n*n),移动速度有些缓慢(low和high考虑了太多情况,其实对于固定长度每个high-low只有一个解)
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <map> #include <assert.h> #include <vector> using namespace std; int num[100000]; void Compute(int val) { int low,high; low =high=1; int sum=1; bool hasAns = false; while (low<=val/2) { if(sum<val) { high++; sum+=high; } else if(sum>val) { sum-=low; low++; } else { hasAns =true; for(int i=low; i<high; i++) printf("%d ",i); printf("%d\n",high); sum-=low; low++; } } if(hasAns) printf("#\n"); else printf("Pity!\n#\n"); } int main() { //freopen("in.txt","r",stdin); int S; while (cin>>S && S>=0) { Compute(S); } return 0; } /************************************************************** Problem: 1354 User: xjbscut Language: C++ Result: Accepted Time:430 ms Memory:1900 kb ****************************************************************/
如前面提到的,对于固定长度每个high-low只有一个解,线性轮训元素数目k,求出相应a0(起始元素表达式),为整数就输出,算法更高效
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <assert.h>
#include <vector>
using
namespace
std;
int
num[100000];
void
Compute(
int
val)
{
bool
hasAns =
false
;
int
maxLen = (
sqrt
(8.0*val+1)-1)/2;
for
(
int
k=maxLen; k>=2; k--)
{
if
((2*val-k*k+k)%(2*k)==0)
{
int
a0 = (2*val-k*k+k)/(2*k);
hasAns =
true
;
for
(
int
i=0; i<k-1; i++)
printf
(
"%d "
,a0+i);
printf
(
"%d\n"
,a0+k-1);
}
}
if
(hasAns)
printf
(
"#\n"
);
else
printf
(
"Pity!\n#\n"
);
}
int
main()
{
//freopen("in.txt","r",stdin);
int
S;
while
(cin>>S && S>=0)
{
Compute(S);
}
return
0;
}
/**************************************************************
Problem: 1354
User: xjbscut
Language: C++
Result: Accepted
Time:140 ms
Memory:1912 kb
****************************************************************/
-
题目描述:
-
输入:
-
输出:
-
样例输入:
-
样例输出: