首页 > 代码库 > HDU 2058 The sum problem
HDU 2058 The sum 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]
思路
((首项+末项)*项数)/2=m以及 末项=首项+项数-1联立方程组可以得到一个关于左区间项,项数,M的一个方程。假设首项是1,我们代入,很容易得到n(n+1)=2m这个公式(n是项数)。 这里可以把n+1看成n,n^2=2m,n=sqrt(2m); 也就是说项数最多的情况也只有sqrt(2m)。大大减小了枚举长度。另外,(a+a+len)*(len+1)/2 = m => a = m/(len+1)-len/2
#include<stdio.h>#include<math.h>int main(){ int N,M,val,len; while (~scanf("%d%d",&N,&M) && N && M) { len = (int)sqrt(2*M); while (len--) { val = M / (len + 1) - len /2; if ((2*val+len) * (len+1) / 2 == M) printf("[%d,%d]\n", val, val+len); } printf("\n"); } return 0;}
HDU 2058 The sum problem
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。