Cod sursa(job #1713742)

Utilizator Cristian1997Vintur Cristian Cristian1997 Data 6 iunie 2016 14:19:21
Problema Progresie Scor 100
Compilator cpp Status done
Runda Arhiva ICPC Marime 1.07 kb
using namespace std;
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
using ll = long long;
using uint = unsigned int;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

ll solve(ll, ll);

int main()
{
	int t, n, r;
	ifstream fin("progresie.in");
	ofstream fout("progresie.out");

	for (fin >> t; t; --t)
	{
		fin >> n >> r;

		fout << solve(n, r) << '\n';
	}

	fin.close();
	fout.close();

    return 0;
}

ll solve(ll n, ll r)
{
	int i, j, d, intv;
	ll low, upp, start, nextEl;
	bool ok;

	for (i = 0; ; ++i)
	{
		start = 1LL * i * (i + 1) + 1;
		d = i;

		for (ok = true, j = 1; j < n && ok; ++j)
		{
			nextEl = start + j * r;
			intv = sqrt(nextEl - 1);

			low = 1LL * intv * (intv + 1) + 1;
			upp = 1LL * (intv + 1) * (intv + 1);

			if (nextEl >= low) { if (d > upp - nextEl) d = upp - nextEl; }
			else if (d < low - nextEl) ok = false;
			else
			{
				d -= low - nextEl;
				start += low - nextEl;
			}
		}

		if (ok) return start;
	}
}