大牛来讨论一下哦

komai908 2009-07-25 08:52:35

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]

http://acm.hdu.edu.cn/showproblem.php?pid=2058
...全文
112 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
abcdef0966 2009-07-26
  • 打赏
  • 举报
回复
#include <stdio.h>
#define MAX 20
int main()
{
int buf1[MAX],buf2[MAX];
int c;
printf("enter your n and m:\n");

for (c = 0; c < MAX; c++)
{
scanf("%d %d",&buf1[c],&buf2[c]);
if ( !buf1[c] && !buf2[c])
break;
c++;
}



int r;
for ( r = 0; r < c; r++)
{
int end,n,m;
n = buf1[r];
m = buf2[r];

end = m < n ? m:n;
int i,j;
for (i = 1; i <= end; i++)
{
int sum = 0;
int k;
k = j = i;
while (sum < m)
sum += j++;
if (sum == m)
printf("[%d %d]\n",k,j-1);
}

printf("\n");
}

return 0;

}
bigbug9002 2009-07-25
  • 打赏
  • 举报
回复
假设从i开始到x之间的整数之和为M,由等比数据求和公式:
(i+x)(x-i+1)/2=M
化简为:x^2+x-i*i-2*M+i=0
由一元二次方程的求根公式,x=(-1+sqrt(1+4*(i*i+2*M-i)))/2,另一个负根舍去。
所以在已知i的情况下可以直接求出x.

做一个i从1到min(N,M)的循环,对每个i求x就可以了。
用数学函数开方的时间效率极低,所以可以自己写一个方法来判断1+4*(i*i+2*M-i)是不是完全平方数。
hua_zhixing_ 2009-07-25
  • 打赏
  • 举报
回复
应该比较简单吧,会不会超时就不知道。
捧剑者 2009-07-25
  • 打赏
  • 举报
回复
up

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧