1. 程式人生 > >nyoj 2100 Graveyard Design

nyoj 2100 Graveyard Design

該題題意是國王要建一個墓地,給出一個面積,看看哪幾個連續數字做正方形的邊,面積加在一起剛好和給出的數字相等。

也就是給出一個數字,找出n段連續的數字,使這n段數字的平方和等於給出的數字。

用尺取法很容易就能做出來。

#include <iostream>
#include <vector>
using namespace std;
struct result {
	long long count;
	long long left;
	long long right;
};
int main()
{
	long long n;
	while (cin >> n)
	{
		long long l = 1;
		long long r = 1;
		long long sum = 0;
		long long sq = 0;
		long long rcount;
		result a;
		vector<result> point;
		while (true)
		{
			while (sum < n)
			{
				sq = r*r;
				sum += sq;
				r++;
			}
			if (sq > n)
				break;
			if (sum == n)
			{
				a.count = r - l;
				a.left = l;
				a.right = r;
				point.push_back(a);
			}
			sum -= l*l;
			l++;
		}
		cout << point.size() << endl;
		for (rcount = 0; rcount != point.size(); rcount++)
		{
			cout << point[rcount].count << " ";
			for (long long i = point[rcount].left; i != point[rcount].right; i++)
			{
				cout << i << " ";
			}
			cout << endl;
		}
	}
}