OJ-HDU The sum problem
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(); } } }