hdu 1075 二分搜索

还是写一下,二分搜索好了

这道题开数组比较坑...

二分,需要注意边界问题,例如:左闭右闭,左闭右开,否则查找不到or死循环


先上AC代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

struct Ch{
    char a[12];
    char b[12];
};

int cmp(const void *aa,const void *bb){
    Ch *x = (Ch *) aa;
    Ch *y = (Ch *) bb;
    return strcmp(x->b,y->b)>0?1:-1;
}

struct Ch ch[500000];
char temp[500000];
int sum=0;

int main(){
    int i=0,j;
    scanf("%s",temp);
    while(scanf("%s",temp),strcmp(temp,"END")!=0){
        strcpy(ch[i].a,temp);
        scanf("%s",ch[i++].b);
        sum++;
    }
    qsort(ch,sum,sizeof(ch[0]),cmp);
    scanf("%s",temp);
    getchar();
    while(gets(temp)!=NULL,strcmp(temp,"END")!=0){
        char t[15]={0};
        j=0; bool is=0;
        for(i=0;i<strlen(temp);i++){
            if((temp[i]>='a'&&temp[i]<='z')||(temp[i]>='A'&&temp[i]<='Z')){
                t[j++]=temp[i];
                is=1;
                if(i!=strlen(temp)-1)
                    continue;
            }
            if(is){
                is=0;
                j=0;
                int l=0,h=sum-1,mid;
                while(l<=h){
                    mid=(l+h)/2;
                    if(strcmp(t,ch[mid].b)>0)
                        l=mid+1;
                    else if(strcmp(t,ch[mid].b)<0)
                        h=mid-1;
                    else if(strcmp(t,ch[mid].b)==0){
                         printf("%s",ch[mid].a);
                        break;
                    }
                }
                if(l>h)
                    printf("%s",t);
                memset(t,0,sizeof(t));
            }
            if(temp[i]<'A'||(temp[i]>'Z'&&temp[i]<'a')||temp[i]>'z')
                printf("%c",temp[i]);
        }
        printf("
");
    }
    return 0;
}


二分法的两种正确代码

1.左闭右闭

int search(int array[], int n, int v)
{
    int mid, l = 0, h = n - 1;

    while (l <= h){
        mid = (l + h) / 2;
        if (array[mid] > v){
            h = mid - 1;
        }
        else if (array[mid] < v){
            l = mid + 1;
        }
        else{
            return mid;
        }
    }
    return -1;
}


2.左闭右开


int search(int array[], int n, int v)
{
    int mid, l = 0, h = n;

    while (l < h){
        mid = (l + h) / 2;
        if (array[mid] > v){
            h = mid;
        }
        else if (array[mid] < v){
            l = mid + 1;
        }
        else{
            return mid;
        }
    }
    return -1;
}



作者:pngcui
博客园:http://www.cnblogs.com/pngcui/
github:https://github.com/pngcui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明。

原文地址:https://www.cnblogs.com/pngcui/p/4335898.html