【HDOJ】2124 Repair the Wall
经典贪心,这样的贪心AC了很多了。
#include <stdio.h> #define MAXNUM 605 int length[MAXNUM]; int comp(const void *a, const void *b) { return *(int *)b - *(int *)a; } int main() { int n, l; int i, tmp, cnt; while (scanf("%d %d", &l, &n) != EOF) { for (i=0; i<n; ++i) scanf("%d", &length[i]); qsort(length, n, sizeof(int), comp); tmp = l; cnt = 0; for (i=0; i<n; ++i) { if (length[i] < tmp) { tmp -= length[i]; cnt++; } else { cnt++; tmp = 0; break; } } if (tmp) printf("impossible\n"); else printf("%d\n", cnt); } return 0; }