HDU2058The sum problem
来源:互联网 发布:sql group by having 编辑:程序博客网 时间:2024/06/17 17:07
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 1050 300 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 10000005int 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
- hdu2058The sum problem
- HDU2058The sum problem
- Sum Problem
- Sum Problem
- sum problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- sum problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- iOS中加数据锁的方式
- @property属性修饰符
- 在iOS 9中不在使用UIAlertView使用UIAlertController
- 文字轮播无缝滚动
- Uart/PCM/IIS
- HDU2058The sum problem
- SSH与jFinal如何决舍
- Web开发学习记录
- iOS中 动态启动图GIF的简单设置 韩俊强的博客
- Android性能优化总结
- 常用的Xcode快捷键
- 非域环境配置ms-sql镜像
- 数据持久化方案(三)ContentProvider
- ubuntu 14.04 初始配置 Mysql+Apache2+PHP