• 10474 Where is the Marble?


    排序,检索;

    使用 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;
    }
  • 相关阅读:
    BZOJ4383 : [POI2015]Pustynia
    BZOJ4382 : [POI2015]Podział naszyjnika
    BZOJ4381 : [POI2015]Odwiedziny
    BZOJ4380 : [POI2015]Myjnie
    BZOJ4378 : [POI2015]Logistyka
    BZOJ3424 : Poi2013 Multidrink
    BZOJ4367 : [IOI2014]holiday假期
    BZOJ4369 : [IOI2015]teams分组
    BZOJ4421 : [Cerc2015] Digit Division
    BZOJ1315 : Ural1557Network Attack
  • 原文地址:https://www.cnblogs.com/JMDWQ/p/2579051.html
Copyright © 2020-2023  润新知