题目
题解思路
数越往前,需要的数字个数就越多,所以直接从前往后找就行了。
这里用了vector二维存最后的答案。
vector用下标访问的时候,这个元素必须已经存在,所以加入新一维数组时,要定义一个临时的数组,然后push_back进去。
这里也可以优化,只存首尾的数字,在输出的时候再遍历。
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;
const int INF = 0x3f3f3f3f;
int main ()
{
ios::sync_with_stdio(false);
long long n;
while(cin>>n)
{
vector < vector <long long > > ans ;
long long t1 = 1 , t2 = 2, sum = 1 ;
while( t1*t1 <= n )
{
if ( sum < n )
{
sum += t2*t2;
t2++;
}else
{
if ( sum == n )
{
vector <long long > tmp ;
for (long long i = t1 ; i < t2 ; i++ )
tmp.push_back(i);
ans.push_back(tmp);
}
sum -= t1*t1;
t1++;
}
// cout<<t1<<" "<<t2<<"\n";
}
cout<<ans.size()<<"\n";
for (int i = 0 ; i < ans.size() ; i++ )
{
cout<<ans[i].size()<<" ";
for (int k = 0 ; k < ans[i].size() ; k++ )
{
cout<<ans[i][k]<<" ";
}
cout<<"\n";
}
}
return 0 ;
}