***HDoj 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]
Author
8600
Source
Recommend
如果按照题意暴力,会超时
根据前n项和公式 Sn = na₁ + n(n-1)/2;
na₁ = Sn - n(n-1)/2 ;
此时假设已知前n项和为m,则
na₁ = m - n(n-1)/2 ;
a₁ =( m - n(n-1)/2 ) / n ;
如果 m - n(n-1)/2 可以被n整除,那么初项 a₁就可以求得出来,子序列末项是 a₁ + n - 1;
要注意,如果n从输入的N开始遍历到1仍然会超时
有题目可知: m - n(n-1)/2 >0
可推出 n <√2m
从 √2m 开始遍历,这样就不会超时
C语言代码如下:
#include<stdio.h> #include<math.h> int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF) { if(n==0&&m==0) break; for(int i=sqrt(2*m);i>=1;i--) { int na1=m- (i*(i-1)/2); if( na1%i == 0 ) printf("[%d,%d]\n",na1/i,na1/i+i-1); } printf("\n"); } }
浙公网安备 33010602011771号