Cod sursa(job #434365)

Utilizator IgrecCorina Popescu Igrec Data 5 aprilie 2010 19:02:57
Problema Gutui Scor 30
Compilator cpp Status done
Runda teme_upb Marime 1.98 kb
#include <stdio.h>
#include <stdlib.h>

#define NMAX 100001

typedef struct item {
	long int poz;
	long int val;
	item *next;
} item;

item *p, *l;
item *pp, *ll;

void adauga (long int j, long int gr) {
	item *nou = new item;
	nou->poz = j; nou->val = gr; nou->next = NULL;
	if (j <= p->poz) {
		nou->next = p; p = nou; return;
	}
	if (j >= l->poz) {
		l->next = nou; l = nou; return;
	}
	item *a, *b; a = p; b = p->next;
	while (j > b->poz) {
		a = b;
		b = b->next;
	}
	nou->next = b;
	a->next = nou;
}

void adauga2 (long int val) {
	item *nou = new item;
	nou->val = val; nou->next = NULL;
	if (val > ll->val) {
		ll->next = nou;
		ll = nou;
		return;
	}
	if (val < pp->val) {
		nou->next = pp;
		pp = nou;
		return;
	}
	item *a, *b; a = pp; b = pp->next;
	while (val > b->val) {
		a = b;
		b = b->next;
	}
	nou->next = b;
	a->next = nou;
}

long int minim (long int v[NMAX], long int i, long int j) {
	if (i == j) return i;
	long int m, a, b;
	m = (i+j)/2;
	a = minim (v, i, m); b = minim (v, m+1, j);
	return (v[a] > v[b]) ? b : a;
}

int main () {

FILE *f, *g;
long int n, hmax, u, h, gr, s=0, i, j;// v[NMAX];


f = fopen ("gutui.in", "r");
g = fopen ("gutui.out", "w");

fscanf (f, "%ld", &n);
fscanf (f, "%ld", &hmax);
fscanf (f, "%ld", &u);

fscanf (f, "%ld", &h);
fscanf (f, "%ld", &gr);

p = new item; l = new item;
p->poz = (hmax-h)/u + 1; p->val = gr; p->next = NULL; l = p;

for (i=2; i<=n; i++) {
	fscanf (f, "%ld", &h);
	fscanf (f, "%ld", &gr);
	j = (hmax - h)/u + 1;
	adauga (j, gr);
}

long int index = 1;
pp = new item; ll = new item;
pp->val = p->val; pp->next = NULL; ll = pp;
s += p->val;
p = p->next;

/*item *aux = new item; aux=p;
while (aux != NULL) {
	printf ("%ld %ld\n", aux->poz, aux->val);
	aux=aux->next;
}*/

while (p != NULL) {
	if (p->poz > index) {
		index++;
		s = s+p->val;
		adauga2(p->val);
		
	}
	else {
		if (p->val > pp->val) {
			s = s-pp->val+p->val;
			pp = pp->next;
			adauga2(p->val);
		}
	}
	p = p->next;
}

fprintf (g, "%ld", s);
	

fclose (f); fclose (g);

return 0;
}