天天看点

POJ2100_Graveyard Design_尺取法::这样写更简洁

Graveyard Design

Time Limit: 10000MS Memory Limit: 64000K
Total Submissions: 6984 Accepted: 1707
Case Time Limit: 2000MS

Description

King George has recently decided that he would like to have a new design for the royal graveyard. The graveyard must consist of several sections, each of which must be a square of graves. All sections must have different number of graves. 

After a consultation with his astrologer, King George decided that the lengths of section sides must be a sequence of successive positive integer numbers. A section with side length s contains s 2 graves. George has estimated the total number of graves that will be located on the graveyard and now wants to know all possible graveyard designs satisfying the condition. You were asked to find them.

Input

Input file contains n --- the number of graves to be located in the graveyard (1 <= n <= 10 14 ).

Output

On the first line of the output file print k --- the number of possible graveyard designs. Next k lines must contain the descriptions of the graveyards. Each line must start with l --- the number of sections in the corresponding graveyard, followed by l integers --- the lengths of section sides (successive positive integer numbers). Output line's in descending order of l.

Sample Input

2030      

Sample Output

2
4 21 22 23 24
3 25 26 27      

给定一个正整数 N, 求数列 A, A 中的所有元素都是相邻的完全平方数, 这样的 A 可能有很多个。

首先输出 A 的种数,然后按长度递减的顺序输出所有方案。

对于每一种方案,先输出元素的个数, 然后输出各元素。

题目本身很简单,这里主要是想说明。

用尺取法时这样一步一步判断左右指针的移动可以使代码简洁很多,但是也相应的牺牲了一些效率。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#define f(x) p[x].first
#define s(x) p[x].second

using namespace std;
typedef long long ll;
typedef pair<int, int> P;

ll N;
vector<P> p;

int main ()
{
	scanf("%lld", &N);

	ll l = 1, r = 1;
	ll sum = 0;

	while(l * l <= N){

		if(sum == N) p.push_back(P(r-l, l));

		if(sum <= N) sum += r * r, r++;
		else sum -= l*l, l++;
	}

	int cnt = p.size();

	sort(p.begin(), p.end());

	printf("%d\n", cnt);

	for(int i= cnt-1; i>= 0; i--){

		printf("%d", f(i));

		for(int j= s(i); j< s(i) + f(i); j++)
			printf(" %d", j);

		printf("\n");
	}

	return 0;
}