POJ 2100 - Graveyard Design(尺取法)

题目:

http://poj.org/problem?id=2100

题意:

是否存在一段连续的数, 平方相加等于n, 求出方案数并输出方案.

思路:

尺取法.

AC.

#include 
#include 
#include 

using namespace std;
typedef long long ll;
int ans[1005], x[1005], y[1005];
ll n;

void solve()
{
    ll m = (ll)sqrt(n*1.0);
    ll k = 1, t = 0;
    ll sum = 0;
    int cnt = 0;
    while(1) {
        while(sum < n) {
            t++;
            sum += (t*t);
        }
        if(t > m) break;
        if(sum == n) {
            ans[cnt] = t - k + 1;
            x[cnt] = k;
            y[cnt] = t;
            cnt++;
        }
        sum -= (k*k);
        k++;
    }
    printf("%d\n", cnt);
    for(int i = 0; i < cnt; ++i) {
        printf("%d", ans[i]);
        //printf(" %d %d\n", x[i], y[i]);
        for(int j = x[i]; j <= y[i]; ++j) {
            printf(" %d", j);
        }
        printf("\n");
    }
}
int main()
{
//freopen("in", "r", stdin);
    while(~scanf("%I64d\n", &n)) {
        solve();
    }
    return 0;
}


你可能感兴趣的:(技巧)