The sum problem
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 30951 Accepted Submission(s): 9261
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]
思路:
原本是直接两个循环再加上求和公式做,果不其然TLE了
后来查了一下网上的做法,优化了许多
设i为子序列起点,j为起点到终点的距离,可以推出(i+i+j-1)*j/2=M
i=(2*M/j+1-j)/2
所以只需要知道距离就可以推出起点的位置
(2*i+j-1)j=2M
根据放缩法则,可以得出j<=sqrt(2*M),只需要遍历一下就行
AcCode:
package hdu经典100题;
import java.util.Scanner;
public class P2058 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
long N = in.nextLong();
long M = in.nextLong();
if(N==0 && M==0) {
break;
}
for (long i = (long) Math.sqrt(2*M); i>0; i--) {
N = ((2*M)/i+1-i)/2;
if((2*N+i-1)*i/2==M) {
System.out.println("["+N+","+(N+i-1)+"]");
}
}
System.out.println();
}
}
}