范德萨发而为
全部博文(392)
分类:
2009-12-29 11:41:05
#include#define EAT 0 #define NOT_EAT 1 #define MIN(a, b) ((a) < (b) ? (a) : (b)) typedef struct _candy { int position; int magic; }ST_CANDY; ST_CANDY candy[51]; int state[51][2]; int cmp(const void *a, const void *b) { ST_CANDY *pa = (ST_CANDY *)a; ST_CANDY *pb = (ST_CANDY *)b; return (pa->position - pb->position); } int bin_search(int front, int rear, int target) { int mid; while (front <= rear) { mid = (rear + front) / 2; if (candy[mid].position >= target) rear = mid - 1; else front = mid + 1; } return front; } int dp(int dst, int size) { int i, position, magic, eat, not_eat, speedup, forward_to, next_candy, next_candy_index; for (i=size-1 ; i>=0 ; i--) { position = candy[i].position; magic = candy[i].magic; /* not eat this candy */ next_candy_index = bin_search(0, size - 1, position + 1); not_eat = (candy[next_candy_index].position - position) * 2 + MIN(state[next_candy_index][EAT], state[next_candy_index][NOT_EAT]); state[i][NOT_EAT] = not_eat; /* eat this candy */ if (position + magic > dst) { state[i][EAT] = state[i][NOT_EAT]; continue; } forward_to = position + magic; if (forward_to > dst) forward_to = position; next_candy_index = bin_search(0, size - 1, forward_to); eat = forward_to - position + (candy[next_candy_index].position - forward_to) * 2 + MIN(state[next_candy_index][EAT], state[next_candy_index][NOT_EAT]); state[i][EAT] = eat; } } int main(int argc, char *argv[]) { int N, M, i, min; while (scanf("%d %d", &N, &M)) { if (0 == N && 0 == M) break; for (i=0 ; i<M ; i++) scanf("%d %d", &candy[i].position, &candy[i].magic); qsort(candy, M, sizeof(ST_CANDY), cmp); candy[M].position = N; state[M][EAT] = state[M][NOT_EAT] = 0; dp(N, M); min = MIN(state[0][EAT], state[0][NOT_EAT]); min += (candy[0].position - 0) * 2; printf("%d ", min); } }