Cod sursa(job #1348454)

Utilizator RanKBrinduse Alexandru RanK Data 19 februarie 2015 18:28:19
Problema Progresie Scor 0
Compilator cpp Status done
Runda Arhiva ICPC Marime 2.01 kb

#define _CRT_SECURE_NO_WARNINGS

#include <stdlib.h>
#include <stdio.h>

#include <math.h>

#define IN_FILE_NAME "progresie.in"
#define OUT_FILE_NAME "progresie.out"

unsigned int CheckNr(unsigned int nr)
{
	unsigned int sqrtInt = (unsigned int)(sqrt(1.0 * nr));
	double sqrtDouble = sqrt(1.0 * nr);

	if(sqrtDouble == sqrtInt) return 0;
	if(nr > sqrtInt * (sqrtInt + 1) && nr < (sqrtInt + 1) * (sqrtInt + 1))
		return 0;

	return sqrtInt * (sqrtInt + 1) + 1 - nr;
}

int main()
{
	freopen(IN_FILE_NAME, "r", stdin);
	freopen(OUT_FILE_NAME, "w", stdout);

	unsigned int tests = 0, t;
	scanf("%d", &tests);

	for(t=0; t<tests; t++)
	{
		unsigned int globalMove = 0;
		bool found = false;
		unsigned int maxMove = 0;
		unsigned int n=0, r=0;
		scanf("%d %d", &n, &r);

		unsigned int i,j;
		for(i=1; i<=(n-1)*r; i++)
		{
			maxMove = 0;
			unsigned int start = 1+i*(i-1)+globalMove;
			unsigned int stop = i*i;
			for(j=start; j<=stop; j++)
			{				
				unsigned int k;
				for(k=1; k<n; k++)
				{
					unsigned int localMove = CheckNr(j+k*r);
					if(maxMove < localMove) maxMove = localMove;
				}
				if(maxMove == 0)
				{
					found = true;
					printf("%d\n", j);
					break;
				}
				else
				{
					// Advance with at least maxMove positions
					if(j + maxMove <= stop) j += maxMove-1; // -1 because the for will increment it
					else
					{
						// find the next i
						unsigned int possibleStart = j + maxMove;

						// find the movement at that cycle						
						i = (unsigned int)(sqrt((possibleStart-1)*1.0));
						
						//if(possibleStart == (i+1)*(i+1))
						//{
						//	i ++;
						//	globalMove = (i*i) - (i*(i-1)) - 1;
						//	i --;
						//}
						if(possibleStart >= i*(i+1) + 1)
							globalMove = possibleStart - i*(i+1) - 1;							
						else
							globalMove = 0;
						break;
					}
				}
			}
			if(found) break;
			//prunsigned intf("\n");
		}
		if(!found)
		{
			printf("%d\n", 1 + ((n-1)*r+1) * ((n-1)*r));
		}
	}	
	return 0;
}