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;
		}
	}
}


你可能感兴趣的:(poj,尺取法)