排序,检索;
使用 bsearch 的 cmp 不能只返回 -1 或 1 (可能是要用差进行比较);
# include <stdio.h> # include <stdlib.h> # include <string.h> # define N 10005 int n, q, a[N], f[N]; int cmp(const void *x, const void *y){return ( *(int*)x - *(int*)y );} int main() { int i, cnt, x; cnt = 0; while (1) { scanf("%d%d", &n, &q); if (!n && !q) break; ++cnt; printf("CASE# %d:\n", cnt); for (i = 0; i < n; ++i) scanf("%d", &a[i]); qsort(a, n, sizeof(a[0]), cmp); memset(f, 0, sizeof(f)); for (i = 0; i < n; ++i) if (!f[a[i]]) f[a[i]] = i+1; for (i = 0; i < q; ++i) { scanf("%d", &x); if (!f[x]) printf("%d not found\n", x); else printf("%d found at %d\n", x, f[x]); } } return 0; }
使用 bsearch :
View Code
# include <stdio.h> # include <stdlib.h> # define N 10005 int n, q, f[N], h[N]; int cmp(const void *x, const void *y) {return *(int*)x - *(int*)y;} int main() { int i, x, *p, cnt; cnt = 0; while (1) { scanf("%d%d", &n, &q); if (!n && !q) break; ++cnt; printf("CASE# %d:\n", cnt); for (i = 0; i < n; ++i) scanf("%d", &f[i]); qsort(f, n, sizeof(f[0]), cmp); for (i = 0; i < q; ++i) { scanf("%d", &x); p = (int*)bsearch(&x, f, n, sizeof(f[0]), cmp); if (p == NULL) printf("%d not found\n", x); else { while (*(--p) == x) ; printf("%d found at %d\n", x, p-f+2); } } } return 0; }