HDU2058-The sum problem

HDU2058-The sum problem

题目:
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]

这道题一开始使用暴力回溯法,结果显示Time Limit Exceeded,后来吧两个for循环的条件改为m / 2,结果还是Time Limit Exceeded。(此时算法复杂度为o(m^2))

后来经过使用求根公式,想通过初始位置求出末位置,期间只用到一个for循环,算法复杂度为o(m),结果还是Time Limit Exceeded。(当时心里真的崩溃了。。。)

代码如下(评测下来Time Limit Exceeded):

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n,m,sum;
    while(~scanf("%d %d",&n,&m))
    {
        if(!n && !m) break;
        for(int i = 1;i < m / 2;i++)
        {
            if((1 + 8 * m + 4 * i * i - 4 * i) > 0)
            {
                double j = (sqrt(1 + 8 * m + 4 * i * i - 4 * i) - 1) / 2.0;
                if(j - (int)j == 0)
					cout << "[" << i << "," << j << "]" << endl;
				else if(j > m / 2) break;
            }
		}
        cout << "[" << m << "," << m << "]" << endl << endl;
    }
    return 0;
}

之后觉得算法复杂度还应该更加低才是,那么只能从for循环中i的终止条件来下手了。此时我将i表示为初始位置,j表示范围的长度。因为该数列是公差为1的等差数列,根据等差数列求和公式可以得出:(i+i+j-1)j/2=m ==>(2i-1+j)j=2m,由此可得j肯定小于等于sqrt(2m)。 然后从长度最长的时候开始列举,通过区域长度j算出初始位置i,随后由if语句判断(还是根据等差数列求和公式进行判断),满足的打印出来就可以了。此时的算法复杂度为o(m^0.5),终于ac。

代码如下:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int n,m,sum;
    while(~scanf("%d %d",&n,&m))
    {
        if(!n && !m) break;
        for(int j = sqrt(2 * m);j > 0;j--)   //j代表区域长度
        {
            int i = ((2 * m) / j + 1 - j) / 2;  //i代表区域的初始点
            if(m == ((2 * i + j - 1) * j) / 2) printf("[%d,%d]\n",i,i + j - 1);
        }
        cout << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41998938/article/details/83477205
今日推荐