Cod sursa(job #127320)

Utilizator alextheroTandrau Alexandru alexthero Data 23 ianuarie 2008 18:57:16
Problema Inundatii Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.2 kb
// sper sa fie sursa de max!

#include <stdio.h>
#include <string.h>

#define nmax 50005
#define abs(x) ((x) > 0 ? (x) : -(x))
#define min(i,j) ((i) > (j) ? (j) : (i))
#define inf (int)1e8

int n;
long long rez;
int x[nmax], y[nmax], z[nmax], a[nmax];

inline long long compute(int x)
{
	long long rez = 0;
	for(int i = 1; i <= n; i++) 
		rez += abs(a[i] - (x + i - 1));
	return rez;
}

long long cauta(int first, int last)
{
	int middle;
	long long aux1, aux2, rez = compute(0);
	while(last - first >= 10)
	{
		middle = (first + last) / 2;
		aux1 = compute(middle);
		aux2 = compute(middle + 1);
		if(aux2 <= aux1)
		{
			rez = min(rez, aux2);
			first = middle + 1;
		}
		else 
		{
			rez = min(rez, aux1);
			last = middle - 1;
		}
	}

	for(int i = first; i <= last; i++) rez = min(rez, compute(i));
	return rez;
}

int main()
{
	freopen("inundatii.in", "r", stdin);
	//freopen("inundatii.out", "w", stdout);
	
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) scanf("%d%d%d", &x[i], &y[i], &z[i]);

	memcpy(a, x, sizeof(x));
	rez += (long long)cauta(-inf, inf);

	memcpy(a, y, sizeof(y));
	rez += (long long)cauta(-inf, inf);

	memcpy(a, z, sizeof(z));
	rez += (long long)cauta(-inf, inf);

	printf("%Ld\n", rez);
	return 0;
}