Cod sursa(job #138233)

Utilizator MariusMarius Stroe Marius Data 17 februarie 2008 23:56:21
Problema Stalpi Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <cstdio>
#include <algorithm>
using namespace std;

const char iname[] = "stalpi.in";
const char oname[] = "stalpi.out";

#define MAXN  100005
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define left(n)   ((n) << 1)
#define right(n) (((n) << 1) + 1)

typedef long long i64;

const i64 inf = (i64)(1e13);

struct entry {
    int cost;
    int low, high;
} A[MAXN];

int n;

int Xc[MAXN];

i64 C[MAXN], T[262144];

bool mycomp(entry a, entry b) {
     return a.high < b.high;
}

void _update(int n, int lo, int hi)
{
     int mid = (hi + lo) >> 1;
     
     if (hi == lo)
         T[n] = C[hi];
     else {
         _update(left(n), lo, mid), _update(right(n), mid + 1, hi);
         T[n] = Min(T[left(n)], T[right(n)]);
     }
}

void update(int n, int lo, int hi, int pos)
{
     int mid = (hi + lo) >> 1;
     
     if (hi == lo)
         T[n] = C[hi];
     else
         pos <= mid ? update(1, lo, mid, pos) : update(1, mid + 1, hi, pos);
}

int query(int n, int lo, int hi, int a, int b)
{
    int mid = (hi + lo) >> 1;
    i64 l = inf, r = inf;
    
    if (a <= lo && hi <= b)
        return T[n];
    if (a <= mid)
        l = query(left(n), lo, mid, a, b);
    if (b > mid)
        r = query(right(n), mid + 1, hi, a, b);
    return Min(l, r);
}
    
int main(void)
{
    FILE *fi, *fo;
    int xmax = 0;
    
    fi = fopen(iname, "r");
    
    fscanf(fi, "%d", &n);
    for (int i = 0; i < n; ++ i)
    {
        int x, c, s, d;
        fscanf(fi, "%d %d %d %d", &x, &c, &s, &d);
        A[i].cost = c;
        A[i].low = x - s;
        A[i].high = x + d;
        if (xmax < x)
            xmax = x;
    }
    
    fclose(fi);
    
    sort(A, A + n, mycomp);
    for (int i = 0; i < n; ++ i)
        Xc[i] = A[i].high;
        
    C[0] = A[0].cost;
    for (int i = 1; i < n; ++ i)
        C[i] = inf;
    _update(1, 0, n-1);
    
    for (int i = 1; i < n; ++ i)
    {
        int j = (int)(lower_bound(Xc, Xc + i, A[i].low - 1) - Xc);
        C[i] = query(1, 0, n-1, j, i-1) + (i64)A[i].cost;
        update(1, 0, n-1, i);
    }
    
    i64 ans = inf;
    for (int i = 0; i < n; ++ i)
        if (A[i].low <= xmax && xmax <= A[i].high)
            if (ans > C[i])
                ans = C[i];

    fo = fopen(oname, "w");
    
    fprintf(fo, "%lld\n", ans);    
    
    fclose(fo);
    
    return 0;
}