The sum problem
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 35412 Accepted Submission(s): 10612
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从0遍历到n-1,次次都TLE,后来把n-1换成sqrt(2*m)就AC了;
原因很简单:
假设符合条件的子串为[a,a+b],有(b+2a)*(b+1)=2m,则b不需要从0遍历到n-1,因为b<sqrt(2*m).
代码如下:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; int main(){ int n, m; int a, b,c; int num; int beg[1000], dis[1000]; char ch1 = '['; char ch2 = ']'; char ch3 = ','; while ((cin >> n >> m), n, m){ num = 0; memset(beg, 0, sizeof(beg)); memset(dis, 0, sizeof(dis)); for (int i = 0; i < sqrt(2*m); i++){ b = i; if ((2 * m) % (b + 1) == 0) c = (2 * m) / (b + 1); else continue; if ((c - b) % 2 == 0) { a = (c - b) / 2; if (a <= 0) continue; } else continue; num++; beg[num] = a; dis[num] = b; } for (int j = num; j >= 1; j--) cout << ch1 << beg[j] << ch3 << dis[j] + beg[j] << ch2 << endl; cout << endl; } return 0; }