杭电2058-----The sum problem

The sum problem
Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 38937 Accepted Submission(s): 11683

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]
这一题我相信很多人都是出现超时了,废话不多说,看看AC代码:

#include<iostream>
#include<algorithm>
#include<string> 
#include<cstdio>
#include<math.h>
using namespace std;
/*
思路:
区间项数为i
起始位置 a,终点为b则b=a+i-1;
这一段区间的和为sum=(a+b)*i/2=(a+a+i-1)*i/2=m;
a最小为1,则(1+1+i-1)*i/2<=m即(i+1)*i<=2m , i有一定小于sqrt(2m)
即 0<i<sqrt(2m);判断条件就是 (a+a+i-1)*i==2*m;
*/
int main()
{
    int n,m,a,b;
    while(cin>>n>>m)
    {
        if(n==0 && m==0)
            break;
        for(int i=sqrt(2*m);i>=1;i--)//最小为1项,就是[m,m] 
        {
            a=m/i-(i-1)/2;//等差公式 即 m=a*i+i*(i-1)/2-----m/i=a+(i-1)/2---a=m/i-(i-1)/2;
            if((a+a+i-1)*i==2*m)
            {
                printf("[%d,%d]\n",a,a+i-1);
            }
        }
        printf("\n");
    }
    return 0;
}

再看看超时代码;

#include<iostream>
using namespace std;
long long n,m,sum=0,k=0;
long long i,j;
int main(){//Time Limit Exceeded
	
	while(cin>>n>>m &&n!=0&&m!=0){
		for(i=1;i<=n;i++){
			k=0,sum=0;
			for(j=i;j<=n;j++){
				sum+=j;
				if(sum==m){
					k++;
					break;
				}
				if(sum>m){
					k=0;break;
				}
			}
			if(k>0){
				cout<<"["<<i<<","<<j<<"]"<<endl;
			}
		}
	}
	return 0;
}

为什么会超时,也很明显,题目中说清楚了N, M( 1 <= N, M <= 1000000000).两个for循环很明显时间复杂度很大,AC代码是采用等差求和公式.
思路:
区间项数为len
起始位置 a,终点为b则b=a+i-1;
这一段区间的和为sum=(a+b)*i/2=(a+a+i-1)*i/2=m;
a最小为1,则(1+1+i-1)*i/2<=m即(i+1)*i<=2m , i有一定小于sqrt(2m)
即 0<i<sqrt(2m);判断条件就是 (a+a+i-1)i==2m

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值