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]
給定一個從1~N的連續區間,求其中的連續區間和,使其等於目標數字。
有一個時間複雜度爲O(N)的算法,其空間複雜度也爲O(N),利用隊列(queue)實現一段區間內加法的和。
#include<stdio.h>
#include<string.h>
#include<iostream>
#define N 1000000010
int queue[N],l,r,sum,solve[N];
int limit ,goal,qujiangeshu;
void write()
{
for(int i=0;i<qujiangeshu;i++)
printf("[%d,%d]\n",solve[i*2],solve[i*2+1]);
puts("");
}
int main()
{
int i;
for(i=1;i<N;i++)
queue[i]=i;
while(scanf("%d%d",&limit,&goal),limit&&goal)
{
l=r=1;sum=queue[1];qujiangeshu=0;
while(l!=limit&&r!=limit){
if(sum==goal){
solve[qujiangeshu*2]=l;
solve[qujiangeshu*2+1]=r;
sum-=queue[l];l++;
qujiangeshu++;
}
else if(sum<goal){
r++;
sum+=queue[r];
}
else if(sum>goal){
sum-=queue[l];
l++;
``
}
}
write();
}
return 0;
}
但是在提交過程中遇到了Memory Limit Exceeded的問題,百度之後仔細分析發現“數組的總大小不得超過 0x7fffffff 字節”,因此,這種方法就變得不可行了。
後來參考網上的一個算法,不考慮子列的終點,而是考慮子列的起點和子列元素的個數,分別記爲i,j。由等差數列求和公式,得(i+(i+j-1))*j/2==M ,即(2*i+j-1)*j/2==M(2式),故得i=(2*M/j-j+1)/2,將i,j代回2式,成立則[i,i+j-1]滿足條件。注意j最小爲1,而由2式,得(j+2*i)*j=2*M,而i>=1,故j*j<=(int)sqrt(2*M)。
這種算法的時間複雜度爲O(Nlog N),但是空間複雜度爲……0。所以很好的解決了我的問題。
開心!
附AC代碼