POJ 2100 Graveyard Design(尺取)

Description
将一个整数分解为连续数平方之和,有多少种分法
Input
一个整数n(1 <= n <= 1014 )
Output
输出所有分法
Sample Input
2030
Sample Output
2
4 21 22 23 24
3 25 26 27
Solution
尺取法
Code

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<functional>
#include<queue>
using namespace std;
typedef long long ll;
vector< pair<ll,ll> >ans;
void solve(ll x)
{
    ll l=1,r=1,sum=0,sq;
    for(;;)
    {
        while(sum<x)
        {
            sq=r*r;
            sum+=sq;
            r++;//右端点右移 
        }
        if(sq>x)
            break;
        if(sum==x)//遇到可行解,记录 
            ans.push_back(make_pair(l,r));
        sum-=l*l;
        l++;//左端点右移 
    }
    ll m=ans.size();//解的个数 
    printf("%lld\n",m);
    for(ll i=0;i<m;i++)//输出所有可行解 
    {
        ll ansl=ans[i].first;
        ll ansr=ans[i].second;
        printf("%lld",ansr-ansl);
        for(int j=ansl;j<ansr;j++)
            printf(" %lld",j);
        printf("\n");
    }
}
int main()
{
    ll n;
    while(scanf("%lld",&n)!=EOF)
    {
        if(n==0)//输入结束条件 
            break;
        solve(n);
    }
    return 0;
}

你可能感兴趣的:(POJ 2100 Graveyard Design(尺取))