晚上放学后没事干准备刷几道题,结果第一道题都不会写了,一道题卡了好久,最后也是没有写出来,唉!好无奈,最后还是看了别人的代码,原来是一道数学类型的题,就是推公式吧,如果你能够推出来,这道题也就写出来了。
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]
Author
8600
Source
这道题的大概意思就是说给你两个数一个m,在1到n这些数找到一些连续的区间,使得这个区间的和的结果等于m,输出所有符合的区间并输出。
这道题如果暴力的话也可以做,,但是吧时间问题啊!!肯定超时啊,然后想到了等差数列的求和公式,可是有两个未知的量,然后就放弃了这种方法(其实吧就是要用等差数列的求和公式的,不过我也是看了别人的推导过程才知道!!)然后又想到了找规律了,结果找了半年也没有找到,没办法只好放弃了,只能百度了,看了别人的代码才知道这原来是一道数学推导数学公式的题,下面给出推导过程。
考虑子串的长度为j,首项为i的数列满足要求,则(i+i+j-1)*j/2=m,==>(2*i-1+j)*j=2m,其中2*i-1>0;所以j*j<2*m;j<sqrt(2*m);这样确定子串的长度了;利用j和m,求出i的表达式,接下来就很简单了:遍历子串的额长度就行了。
下面给出AC代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n,m,i;
while(scanf("%d %d",&n,&m)&&(n||m))
{
int j=sqrt((double)2*m);
for(;j>=1;j--)
{
i=(2*m/j+1-j)/2;
if((2*i-1+j)*j/2==m)
printf("[%d,%d]\n",i,i+j-1);
}
printf("\n");
}
return 0;
}
怎么说呢?还是能力不够吧,继续努力吧!!!!!!!!!!!