poj2503 hash
src:http://poj.org/problem?id=2503
ac代码:
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<stdio.h> #include <cstdlib> #include<malloc.h> #include<algorithm> #include<functional> #include<utility> #include<cmath> #include<Map> #include<string.h> #include<string> #include<vector> #include<stack> #include<set> #include<queue> #include<list> #define FOR(i,a,b) for(int i=a;i<=b;i++) using namespace std; #define siz 100005 #define inf 99999999 struct { char s1[11], s2[11]; int ne; }node[siz]; int hashmap[siz]; char ans[11]; int Enum; void init() { Enum = 0; memset(hashmap, -1, sizeof(hashmap)); } unsigned int ELF_hash(char*s) { unsigned int hash = 0, x = 0; while (*s) { hash = (hash << 4) + (*s);//hash左移4位加上*s x = hash & 0xf0000000L;//取出高四位 if (x != 0) { hash ^= x >> 24;//用高四位来处理5-8位,低四位刚来不要搞他先~~~ //抑或0时不变,抑或1时变 hash &= ~x; } s++; } return hash % 10001; } void Insert_Hash(char*s1, char*s2) { int key = ELF_hash(s2); strcpy(node[Enum].s1, s1); strcpy(node[Enum].s2, s2); node[Enum].ne = hashmap[key]; hashmap[key] = Enum++; } int find(char *t) { int key = ELF_hash(t); bool flag = false; for (int i = hashmap[key]; i != -1; i = node[i].ne) { if (strcmp(node[i].s2, t)==0) { flag = true; return i; } } if (!flag)return -1; } void solve() { char t[11]; while (cin >> t) { int ee = find(t); if (ee == -1)cout << "eh" << endl; else cout << node[ee].s1 << endl; } } int main() { ios::sync_with_stdio(false); char s1[11], s2[11], str[22]; init(); while (cin.getline(str, 22)) {//cin>>string会跳过空行,,单独读取一整行就不会,上一行已经把他自己的换行符吃了 if (str[0] == '\0')break; //\0 空 sscanf(str, "%s %s", s1, s2); Insert_Hash(s1, s2); } solve(); return 0; }

浙公网安备 33010602011771号