POJ 2503 快速排序+二分 / 雜湊查詢
阿新 • • 發佈:2019-01-10
快速排序+二分:
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> typedef long long int ll; #define PI 3.14159265358979323846 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3fll #define maxn 100000+5 #define mod 2000120420010122 #define eps 1e-7 using namespace std; typedef struct{ char english[11]; char foreign[11]; }node; node a[maxn]; int cnt=0; int cmp(const void *a, const void *b){ return strcmp((*(node *)a).foreign, (*(node *)b).foreign); } int BinSearch(char str[]){ int left=0, right=cnt-1; int mid, tmp; while(left<=right){ mid=(left+right)/2; tmp=strcmp(str, a[mid].foreign); if(tmp==0){ // return mid; }else if(tmp>0){ left=mid+1; }else{ right=mid-1; } } return -1; } int main(int argc, char const *argv[]){ char str[25]; while(gets(str)){ if(str[0]=='\0') break; sscanf(str,"%s%s",a[cnt].english,a[cnt].foreign); cnt++; } qsort(a, cnt, sizeof(a[0]), cmp); /* for(int i=0;i<cnt;i++){ cout<<a[i].english<<" "<<a[i].foreign<<endl; } */ int flag=-1; while(gets(str)){ //cout<<str<<endl; flag=BinSearch(str); if(flag==-1){ printf("eh\n"); }else{ printf("%s\n",a[flag].english); } } }
雜湊:
#include <iostream> #include <cstdio> #include <fstream> #include <algorithm> #include <cmath> #include <deque> #include <vector> #include <queue> #include <string> #include <cstring> #include <map> #include <stack> #include <set> typedef long long int ll; #define PI 3.14159265358979323846 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3fll #define maxn 149993 #define eps 1e-7 using namespace std; int ELFhash(char *key){// unsigned long h=0; while(*key){ h=(h<<4)+(*key++); unsigned long g = h & 0Xf0000000L;// if(g){ h ^= g>>24; } h &= ~g; } return h % maxn; } typedef struct{ char english[11]; char foreign[11]; int next; }node; node a[maxn]; int cnt=1; int hashIndex[maxn]; void solve(char f[]){ int hash=ELFhash(f); for(int k = hashIndex[hash]; k; k = a[k].next){ if(strcmp(f, a[k].foreign) == 0){ printf("%s\n",a[k].english); return; } } printf("eh\n"); } int main(int argc, char const *argv[]){ char str[25]; while(gets(str)){ if(str[0]=='\0'){ break; } sscanf(str, "%s%s",a[cnt].english,a[cnt].foreign); int hash=ELFhash(a[cnt].foreign); a[cnt].next=hashIndex[hash]; hashIndex[hash]=cnt; cnt++; } while(gets(str)){ solve(str); } }