首页 > 代码库 > POJ3349
POJ3349
Hash table经典算法
以前写的算法, 用时1860ms
#include <iostream> #include <string> using namespace std; #define HASHLEN 202099 #define SNOWNUM 100001 struct Node { int arms[6]; int next; }; Node snow[SNOWNUM]; int hashTable[HASHLEN]; bool cmp(int *armsx, int *armsy){ int i, j; for (i = 0; i < 6; i++) { for (j = 0; j < 6; j++) { if (armsx[j] != armsy[(i+j)%6]) break; } if (j == 6) return true; } for (i = 0; i < 6; i++) { for (j = 0; j < 6; j++) { if (armsx[j] != armsy[(6+i-j)%6]) break; } if (j == 6) return true; } return false; } int main() { int n, cnt, hVal, idx, pre, i, j; scanf("%d",&n); memset(hashTable, 0x00, sizeof(hashTable)); for (i = 1; i <= n; i++) { cnt = 0; //input data snow[i].next = 0; for (j = 0; j < 6; j++) { scanf("%d",&snow[i].arms[j]); cnt += snow[i].arms[j]; } //calc hash key hVal = cnt % HASHLEN; //insert to hashtable idx = hashTable[hVal]; if (idx > 0) { do { pre = idx; //Compare same snowflake if (cmp(snow[i].arms, snow[pre].arms)) { cout << "Twin snowflakes found." << endl; return 0; } idx = snow[idx].next; } while (idx > 0); snow[pre].next = i; } else { hashTable[hVal] = i; } } cout << "No two snowflakes are alike." << endl; return 0; }
POJ3349
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。