Cod sursa(job #1760955)

Utilizator CataFetoiuFetoiu Catalin CataFetoiu Data 21 septembrie 2016 16:57:45
Problema Progresie Scor 0
Compilator cpp Status done
Runda Arhiva ICPC Marime 1.34 kb
#include<cstdio>
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<sstream>
#include<limits.h>
#include<math.h>
#include<list>
#include<queue>
#include<map>

using namespace std;

typedef pair<int, int> ii;

#define Max 3100
#define INF 2000000000

/* last element in union */
int f(int seq)
{
	return seq * (seq+1);
}

/* first element in sequence */
int first(int seq)
{
	return f(seq-1) + 1;
}

/* last element in sequence */
int last(int seq)
{
	return first(seq) + seq - 1;
}

/* finds min j such that first(j) >= a */
int find(int a)
{
	int x = floor(sqrt(a-1));
	if(x * (x+1) >= a)
		return (x+1);
	else
		return (x+2);
}

int main()	
{
	FILE* fin = freopen("progresie.in", "r", stdin);
	FILE* fout = freopen("progresie.out", "w", stdout);

	int T; cin >> T;
	while(T--)
	{

	int N, R;
	cin >> N >> R;
	if(N == 1)
		cout << "1" << endl;
	else if(N == 2)
	{
		int res = first(1 + (N-1) * R);
		int i = 0;
		while(true)
		{
			i++;
			if(i >= R)
				break;
			
			int a = first(i) + R; /* max reachable interval from sequence i */
 			int b = last(i) + R;

			int j = find(a);
			if(first(j) <= b)
			{
				res = min(res, first(j) - R);
				break;
			}
		}
		cout << res << endl;
	}
	else
	{
		cout << first(1 + (N-1) * R) << endl;
	}

	}

	fclose(fin);
	fclose(fout);

	return 0;
}