VJ基础练习题二 U - The sum problem

VJ基础练习题二
U - The sum problem
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]

输入N,M,求1-n的序列中,和是M的子序列。

Time Limit Exceeded

#include<iostream>
#include<string>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
	int n,m;
	while(cin>>n>>m){
		if(n==0&&m==0){
			break;
		}
		for(int i=1;i<=n;i++){
			for(int j=i;j<=n;j++){
				double sum = (j-i+1)*(j+i)/2;
				if(sum == m){
					cout<<"["<<i<<","<<j<<"]\n";
					break; 
				}
				if(sum > m){
					break;
				}
			}
		}
		cout<<endl;
	}
    return 0;
}

Memory Limit Exceeded

#include<iostream>
#include<string>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
	int n,m;
	while(cin>>n>>m){
		if(n==0&&m==0){
			break;
		}
		double sum[n+1];
		sum[0]=0;
		for(int i=1;i<=n&&i<m;i++){
			sum[i]=sum[i-1]+i;
		}
		
		for(int i=1;i<=n;i++){
			for(int j=i;j<=n;j++){
				double s = sum[j]-sum[i-1];
				if(s == m){
					cout<<"["<<i<<","<<j<<"]\n";
					break; 
				}
				if(s > m){
					break;
				}
			}
		}
		cout<<endl;
	}

    return 0;
}

Accepted

#include<iostream>
using namespace std;

int main()
{
	int n,m;
	while(cin>>n>>m){
		if(n==0&&m==0){
			break;
		}
		for(int len=pow(2*m,0.5);len>=1;len--){
			int beg = (2*m/len+1-len)/2;
			if((beg*2+len-1)*len==2*m){
				printf("[%d,%d]\n",beg,beg+len-1);
			}
		}
		cout<<endl;
	}
    return 0;
}
VJ基础练习题二 U - The sum problemVJ基础练习题二 U - The sum problem RY_zeze 发布了17 篇原创文章 · 获赞 0 · 访问量 84 私信 关注
上一篇:hdu6162


下一篇:洛谷CF161D