Cod sursa(job #230926)

Utilizator mugurelionutMugurel-Ionut Andreica mugurelionut Data 14 decembrie 2008 10:59:13
Problema Tablete Scor 100
Compilator cpp Status done
Runda Algoritmiada 2009, Runda 1, Clasele 9-10 Marime 1.72 kb
#include <stdio.h>
#include <string.h>
//#include <time.h>

#define NMAX 1001
#define LMAX 20001

int A[NMAX][NMAX];
char buf[LMAX];
int N, K, t1;

void print_matrix(void)
{
	int i, j, x, c = 0, cnt, next;

	for (i = 1; i <= N; i++)
	{
		buf[c = 0] = 0;
		for (j = 1; j <= N; j++)
		{
			x = A[i][j];

			if (x >= 1000000)
				cnt = 6;
			else
			if (x >= 100000)
				cnt = 5;
			else
			if (x >= 10000)
				cnt = 4;
			else
			if (x >= 1000)
				cnt = 3;
			else
			if (x >= 100)
				cnt = 2;
			else
			if (x >= 10)
				cnt = 1;
			else
				cnt = 0;

			next = cnt + 1;

			while (x > 0)
			{
				buf[c + cnt] = '0' + (x % 10);
				x /= 10;
				cnt--;
			}
			
			c += next;

			if (j < N)
			{
				buf[c] = ' ';
				c++;
			}
		}

		buf[c] = '\n';
		buf[c + 1] = 0;

		printf("%s", buf);
	}
}

void build_solution()
{
	int i, row, p, next, vmin;

	p = N * K;
	for (i = p, row = N; i >= 1 && row > 0; i--)
		if (i % 2 == 0)
		{
			A[row][K] = i;
			vmin = i;
			row--;
		}

	// left half
	next = 0;
	for (row = 1; row <= N; row++)
		for (i = 1; i < K; i++)
		{
			next++;
			while ((next >= vmin) && ((next & 1) == 0))
				next++;

			A[row][i] = next;
		}

	//right half
	next = p;

	for (row = 1; row <= N; row++)
		for (i = K + 1; i <= N; i++)
		{
			next++;
			A[row][i] = next;
		}

	if (p % 2 == 1)
	{
		// make a swap
		next = A[1][K + 1];
		A[1][K + 1] = A[N][K];
		A[N][K] = next;
	}
}

int main()
{
	//t1 = clock();

	freopen("tablete.in", "r", stdin);
	freopen("tablete.out", "w", stdout);

	scanf("%d %d", &N, &K);

	build_solution();
	print_matrix();

	//fprintf(stderr, "duration=%d\n", clock()- t1);

	return 0;
}