zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    Java:day11
    Java:day10
    Java:day9
    Java:day8
    纯虚函数和抽象类
    C++的虚拟继承
    派生类构造函数、析构函数的定义和调用次序
    c++的继承方式——公有、保护、私有
    操作系统中系统调用的执行过程
    C++的类
  • 原文地址:https://www.cnblogs.com/hushpa/p/6244627.html
Copyright © 2011-2022 走看看