HDOJ 2058 The sum problem

本文探讨了给定序列中所有可能子序列之和等于特定数值的问题,介绍了一种高效算法,利用数学知识减少计算复杂度,并给出了具体的实现代码。

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

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]

解题思路:

这个题输入的数据可以很大,所以最简单粗暴的方法就不能用了,会timeout。
所以这个题可以换一个思路来做,首先需要知道一个数学知识:

1+2+3++2m>m1+2+3+⋯+2m>m

所以和为m的元素的个数最多不超过 2m2m 个,最少有 1 个。

接下来就可以用for循环,通过序列元素的个数来进行计算。
而这个计算需要用到等差数列求和公式:

Sn=a1n+n(n1)2dnNSn=a1n+n(n−1)2d,n∈N∗

a1a1 为首项,n为项数,d为公差,那么求首项的变形公式为:

a1=Snnn12da1=Snn−n−12d

通过上式即可求出首项 a1a1,那么最后一项就是 a1+n1a1+n−1,即 [a1,a1+n1][a1,a1+n−1].

代码:

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    long long n,m,a;
    while(cin>>n>>m && n||m)
    {
        for(int i=sqrt(2*m); i>0; i--)
        {
            a=m/i-(i-1)/2;
            //需检查i是否为整数。
            if(a*i+i*(i-1)/2==m)
                cout<<'['<<a<<','<<a+i-1<<']'<<endl;
        }
        cout<<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值