hdu 2058 The sum problem

链接:http://hdu.hustoj.com/showproblem.php?pid=2058

The sum problem

Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23527    Accepted Submission(s): 6998


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

看着很简单的题,求1-n中连续的几个和是m的数

错误原因:超时

也想过(首相+末项)*项数/2==m,但是推出来还是要两个for循环,嗖的就超时了,看了discuss,没太看明白,有知道的dalao可以给讲讲,推公式真的不在行

暂且放其他人的代码和题解:

1.

//等差数列求前n项和————Sn=na1+((n-1)*n*d)/2
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    long long int m,n,a;
    while(cin>>n>>m)
    {
        if(n==0&&m==0)
            break;
        for(int i=sqrt(2*m);i>0;i--)//保证a1的值大于0
        {
            a=m/i-(i-1)/2;
            if((2*a+i-1)*i==2*m)
                cout<<"["<<a<<","<<a+i-1<<"]"<<endl;
        }
        cout<<endl;
    }
    return 0;
}

2.

((首项+末项)*项数)/2=m以及 末项=首项+项数-1联立方程组可以得到一个关于左区间项,项数,M的一个方程。

(高中课程,不详细展开了)

假设首项是1,我们代入,很容易得到n(n+1)=2m这个公式(n是项数)。 这里可以把n+1看成n,n^2=2m,
n=sqrt(2m); 也就是说项数最多的情况也只有sqrt(2m)。

这也就是说,假设M给的是10的9次方,最大的答案区间撑死也只有46000左右的长度。也就是2的10次的算术平方根


那么我们枚举1---sqrt(2m),假设是长度代入到公式中。m知道了,长度知道了,那么可以解出首项,我们知道,这个数列的每一项必定是个正整数,那么如果算出来的首项正好是个正整数,那么就是个答案,

区间就是【我们算出来的整数,整数+长度-1】输出即可。
(我是不是傻了,没怎么看懂)

代码:

#define _CRT_SBCURE_MO_DEPRECATE    
#include<iostream>    1
#include<stdlib.h>    
#include<stdio.h>    
#include<cmath>    
#include<algorithm>    
#include<string>    
#include<string.h>    
#include<set>    
#include<queue>    
#include<stack>    
#include<functional>     
using namespace std;
const int maxn = 1000000 + 10;
const int maxm = 10000 + 10;
const int INF = 0x3f3f3f3f;

int n, m;
int a, len;
double x;

int main()
{
	while (scanf("%d %d", &n, &m) != EOF && n && m) {
		len = floor(sqrt(2 * m));
		for (int i = len; i >= 1; i--) {
			x = 1.0*(2 * m) / i + 1 - i; 
			x = 0.5*x;
			a = floor(x);//向下取整
			x = x - a;
			if (x == 0 && a <= n && (a + i - 1) <= n) { printf("[%d,%d]\n", a, a + i - 1); }
		}
		printf("\n");
	}
	system("pause");
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值