HDU2058The sum problem

The sum problem

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


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]
 
注意:题目的数据量 ( 1 <= N, M <= 1000000000) 特别大;

刚开始看求区间的和以为可以用树状数组去做,结果看了数据量和题目意思之后就没想法了。后来发现是个等差数列,就从等差数列的公式考虑起来了;

我们假设满足题意的区间的起始的位置为 x,那么则有 (x+0)+(x+1)+(x+2)+......+(x+n)=m;
将上式变形可得: (x+x....+x)+(0+1+2+.....+n)=m;  令Sn=0+1+2+....+n;
继续变形得: (n+1)*x+Sn=m;
继续变形得: x=(m-Sn)/(n+1);
最后我们只要判断这个 x 是否属于题目所给出的范围内的数,并且要保证其为正整数就好了;
那么这个满足要求的区间的起始位置就求出来了,终点位置也就求出来了,为: x+n;

欢迎大家积极踊跃的提问o0o;
给出AC代码:
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
#define MAX 10000005
int a[MAX], b[MAX];
int main()
{
	
	int m, n;
	int k;
	int count=0;
	double y;
	long long sn;
	while (cin >> n >> m)
	{
		k = 0;
		if (n == 0 && m == 0)break;
		for (int i = 0; i <= n; i++)
		{
			sn = (1 + i)*i / 2;
			y = (m - sn)*1.0 / (i + 1);
			if (sn > m)break;
			if (int(y) - y == 0&&sn<m)
			{
				if (y != 0)
					a[k] =(int)y, b[k++] = i + (int)y;
			}
		}
		for (int i = k - 1; i >= 0; i--)
			cout << "[" << a[i] << "," << b[i] << "]" << endl;
		cout << endl;
	}
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值