Cod sursa(job #168815)

Utilizator DITzoneCAdrian Diaconu DITzoneC Data 31 martie 2008 19:58:08
Problema Wanted Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.21 kb
#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

#define nmax 256
#define FOR(i,s,d) for(i=(s);i<(d);++i)
#define inf 1000111000
#define f first
#define s second

pair <int,int> P[nmax];
int n,A[nmax][nmax],B[nmax][nmax],sol;

inline int MIN(int a,int b) { return a<b?a:b; }
inline int MAX(int a,int b) { return a>b?a:b; }

inline int dt1(int a)
{
	if(a<0||a>=n) return inf;
	return (P[a].f>0?P[a].f:-P[a].f)+P[a].s;
}

inline int dt(int a,int b)
{
	if(a<0||a>=n||b<0||b>=n) return inf;
	if(a==b) return 0;
	return (P[b].f>P[a].f?P[b].f-P[a].f:P[a].f-P[b].f)+P[a].s+P[b].s;
}

int getc(int i,int j,int k)
{
	if(k==0) return A[1][j];
	if(k==n-1) return B[i][k-1];
	return MAX(A[k+1][j],B[i][k-1]);
}

int main()
{
	freopen("wanted.in","r",stdin);
	freopen("wanted.out","w",stdout);
	scanf("%d",&n);
	int i,j,l,k;
	FOR(i,0,n)
	{
		scanf("%d %d",&P[i].f,&P[i].s);
		if(P[i].s<0) P[i].s=-P[i].s;
	}
	sort(P,P+n);
	FOR(l,0,n) FOR(i,0,n)
	{
		j=i+l;
		if(j>=n) break;
		A[i][j]=B[i][j]=inf;
		FOR(k,i,j+1)
		{
			A[i][j]=MIN(A[i][j],getc(i,j,k)+dt(i-1,k));
			B[i][j]=MIN(B[i][j],getc(i,j,k)+dt(j+1,k));
		}
	}
	sol=A[1][n-1]+dt1(0);
	FOR(i,1,n)
		sol=MIN(sol,getc(0,n-1,i)+dt1(i));
	printf("%d\n",sol);
	return 0;
}