思路:
有油的時候能走多遠就走多遠,看能否走到目的地。
如果走不到,就必須要加一次油,途中會遇到很多加油站,一定要選油最多的那個。
這很容易理解,因為如果你只加這一次,越多當然越好。如果要以后還要加,那能走遠一點選擇也多一點。
重復這樣的過程就可以求解了。可以用堆維護加油站中的油量。
杯具:稍稍修改了一下堆的寫法,結果WA兩次。。
代碼:
#include <stdio.h>
#include <stdlib.h>

#define MAX_N 10032


struct node
{
int x, f;
};

struct node stop[MAX_N];
int N, L, P;
int heap[MAX_N], heap_size;

inline void shift_up(int idx)


{
int val = heap[idx];

while (idx > 1 && heap[idx/2] < val)
{
heap[idx] = heap[idx/2];
idx /= 2;
}
heap[idx] = val;
}

inline void shift_down(int idx)


{
int val = heap[idx];

while (1)
{
idx *= 2;
if (idx > heap_size)
break;
if (idx + 1 <= heap_size && heap[idx + 1] > heap[idx])
idx++;
if (val >= heap[idx])
break;
heap[idx/2] = heap[idx];
}
heap[idx/2] = val;
}

int cmp(const void *a, const void *b)


{
return ((struct node *)b)->x - ((struct node *)a)->x;
}

inline void push(int val)


{
heap[++heap_size] = val;
shift_up(heap_size);
}

inline void pop()


{
heap[1] = heap[heap_size--];
shift_down(1);
}

int main()


{
int i, x, t;

freopen("e:\\test\\in.txt", "r", stdin);

scanf("%d", &N);
for (i = 0; i < N; i++)
scanf("%d%d", &stop[i].x, &stop[i].f);
scanf("%d%d", &L, &P);
qsort(stop, N, sizeof(stop[0]), cmp);

push(P);
x = L;
i = 0;

for (t = 0; heap_size && x > 0; t++)
{
x -= heap[1];
pop();
while (i < N && x <= stop[i].x)
push(stop[i++].f);
}
printf("%d\n", x <= 0 ? t - 1 : -1);

return 0;
}
