HDUOJ 2058 The sum problem
Problem Description
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
Input contains multiple test cases. each case contains two integers N, M( 1 <= N, M <= 1000000000).input ends with N = M = 0.
Output
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.
Sample Input
20 10
50 30
0 0
Sample Output
[1,4]
[10,10]
[4,8]
[6,9]
[9,11]
[30,30]
刚开始很高兴写出了暴力解,结果超时,于是寻找效率更高的方法,使用等差数列求和验证
首项和最大项数有点不好理解, 对于最大项数只模拟起点和数列的长度,知道起点i和数列长度j,很容易根据等差数列公式求得这个子序列的和:(i+(i+j-1)) * j/2; 化简公式得:
j * j+(2 * i - 1)=2 * m;因为i>=1,m已知,所以j的取值为:j<=sqrt(2*m) ;实际是数学问题,下面贴出找到比较好的首项求法解释:
AC源码:
#include<cstdio>
#include<cmath>
int main()
{
int n,m,s,e,num;
while(scanf("%d%d",&n,&m),n,m)
{
for(num=sqrt(2.0*m);num>=1;--num) //num为项数 最多为 pow(2.0*m,0.5)
{
s=(2*m/num+1-num)/2; //首项 (其最小为 1 )
e=s+num-1; //尾项
if((s+e)*num/2==m) //计算过程有取整,要判断是否满足
printf("[%d,%d]\n",s,e);
}
printf("\n");
}
return 0;
}
下面贴出暴力解
#include<stdio.h>
int main() {
int n,m,i,j,sum,p;
while(~scanf("%d %d",&n,&m) && n||m) {
for(i=1; i<=n; i++) {
sum =0;
p=0;
for(j=i; j<=n; j++) {
sum+=j;
if(sum==m) {
p=1;
break;
}
if(sum>m)
break;
}
if(p)
printf("[%d,%d]\n",i,j);
}
printf("\n");
}
return 0;
}