二分法在顺序排列的字典中查找单词(二分)
生活随笔
收集整理的這篇文章主要介紹了
二分法在顺序排列的字典中查找单词(二分)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
用二分法在順序排列的字典中查找單詞
typedef struct{ char word[20];/*單詞名*/int count; /*單詞計(jì)數(shù)器*/}KeyTab; KeyTab tab[M];
若找到,該單詞計(jì)數(shù)器增1;若沒找到,字典新增一個(gè)單詞
根據(jù)題意自己寫的代碼,有可能有些錯(cuò)誤,大家借鑒著看一下吧。
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define inf 0x3f3f3f3f #define M 1010typedef struct{char word[20];int count; }KeyTab; KeyTab tab[M];int main() {int i;for(i=0;i<M;i++) tab[i].count=0,memset(tab[i].word,'\0',sizeof(tab[i].word));//初始化char s[20];int cnt=0;//單詞計(jì)數(shù) printf("請(qǐng)依次輸入單詞\n");while(1){scanf("%s",s);if(strcmp(s,"#")==0) break;if(cnt==0) tab[0].count++,strcpy(tab[0].word,s),cnt++;else{int l=0,r=cnt-1,mid,pos;while(l<=r)//二分{mid=l+r>>1;if(strcmp(tab[mid].word,s)<0) l=mid+1;else if(strcmp(tab[mid].word,s)>0) r=mid-1;else break;}if(strcmp(tab[mid].word,s)==0) tab[mid].count++;else{for(i=cnt;i>l;i--) tab[i]=tab[i-1];strcpy(tab[l].word,s);tab[l].count=1;cnt++;}}}for(i=0;i<cnt;i++) printf("%s %d\n",tab[i].word,tab[i].count);return 0; }主要是對(duì)二分法和結(jié)構(gòu)體的考察。
努力加油a啊,(o)/~
總結(jié)
以上是生活随笔為你收集整理的二分法在顺序排列的字典中查找单词(二分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Educational Codeforc
- 下一篇: Generate a String Co