HDUOJ 2058 The sum problem

这篇博客探讨了如何通过等差数列的性质优化解决寻找特定和的子序列问题。作者首先分享了暴力求解方法,但发现这种方法在大数据量下会超时。接着,他们转向了等差数列的思路,通过计算首项和最大项数来提高效率,最终实现了AC(Accepted)的解决方案。博客中还提供了暴力解和优化解的代码示例,供读者参考学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值