Cod sursa(job #137246)

Utilizator gcosminGheorghe Cosmin gcosmin Data 17 februarie 2008 10:33:17
Problema Stalpi Scor 60
Compilator cpp Status done
Runda preONI 2008, Runda 4, Clasele 11-12 Marime 2.12 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;

#define NMAX 100010
#define LL long long
#define ff first
#define ss second

int N, stepmax;

pair <pair<int, int>, pair<int, int> > a[NMAX];

int b[NMAX];

LL aint[(1 << 18) + 100];

inline LL LMIN(LL a, LL b) { return (a < b) ? a : b; }

void make_arb(int x, int y, int q)
{
	if (x == y) {
		aint[q] = 1LL << 62;
		return;
	}

	int mij = (x + y) >> 1;

	make_arb(x, mij, q << 1);
	make_arb(mij + 1, y, (q << 1) + 1);

	aint[q] = 1LL << 62;
}	

void update(int x, int y, int q, int poz, int val)
{
	if (x == y) {
		if (val < aint[q]) aint[q] = val;
		return;
	}

	int mij = (x + y) >> 1;

	if (poz <= mij) update(x, mij, q << 1, poz, val);
	else update(mij + 1, y, (q << 1) + 1, poz, val);

	aint[q] = LMIN(aint[q << 1], aint[(q << 1) + 1]);
}

LL query(int x, int y, int q, int a, int b)
{
	if (a <= x && y <= b) return aint[q];

	int mij = (x + y) >> 1;
	LL f1 = 1LL << 62, f2 = 1LL << 62;

	if (a <= mij) f1 = query(x, mij, q << 1, a, b);
	if (b > mij) f2 = query(mij + 1, y, (q << 1) + 1, a, b);

	return f1 < f2 ? f1 : f2;
}

int srch(int val)
{
	int x = 0, step = stepmax;

	for (; step; step >>= 1)
		if (x + step <= N && b[x + step] <= val) x += step;

	return x;
}

int beg;
char s[200];

inline void GET(int &x)
{
	for (; s[beg] && !('0' <= s[beg] && s[beg] <= '9'); beg++);

	for (x = 0; '0' <= s[beg] && s[beg] <= '9'; beg++)
		x = x * 10 + s[beg] - '0';
}

int main()
{
	int i, x, y;

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

	scanf("%d\n", &N);

	for (i = 1; i <= N; i++) {
		fgets(s, 200, stdin);
		beg = 0;
		GET(a[i].ff.ff);
		GET(a[i].ff.ss);
		GET(a[i].ss.ff);
		GET(a[i].ss.ss);
//		scanf("%d %d %d %d", &a[i].ff.ff, &a[i].ff.ss, &a[i].ss.ff, &a[i].ss.ss);
	}

	sort(a + 1, a + N + 1);

	make_arb(1, N, 1);

	for (i = 1; i <= N; i++) b[i] = a[i].ff.ff;
	for (stepmax = 1; stepmax <= N; stepmax <<= 1);

	for (i = 1; i <= N; i++) {
		x = srch(a[i].ff.ff - a[i].ss.ff - 1);
		y = srch(a[i].ff.ff + a[i].ss.ss);

		update(1, N, 1, y, (!x ? 0 : query(1, N, 1, x, N)) + a[i].ff.ss);
	}

	printf("%lld\n", query(1, N, 1, N, N));

return 0;
}