POJ3349 Snowflake Snow Snowflakes(哈希)

题目链接

分析:

哈希竟然能这么用。检查两片雪花是否相同不难,但如果是直接暴力,定会超时。所以要求哈希值相同时再检查。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <ctime>

using namespace std;

const int maxn = 100000+10;
const int MOD_VAL = 97777;

int sn[maxn][6];
vector<int>hash[MOD_VAL];

bool check(int a, int b) {  //检查两片是否相等
    for(int i=0; i<6; i++) {
        bool flag = true;
        for(int j=0; j<6; j++) {
            if(sn[a][j] !=sn[b][(i+j)%6]) {
                flag = false; break;
            }
        }

        if(flag == true) return true;

        flag = true;
        for(int j=0; j<6; j++) {
            if(sn[a][j] != sn[b][(i-j+6)%6]) {
                flag = false; break;
            }
        }

        if(flag == true) return true;
    }

    return false;
}

int main() {
    int n; bool flag = false;

    scanf("%d", &n);
    for(int i=0; i<n; i++) {
        for(int j=0; j<6; j++) {
            scanf("%d", &sn[i][j]);
        }
    }

    for(int i=0; i<n; i++) {
        int sum = 0;
        for(int j=0; j<6; j++) sum += sn[i][j];
        int key = sum % MOD_VAL;
        for(int j=0; j<hash[key].size(); j++) {
            //check
            if(check(hash[key][j], i)) {
                flag = true; break;
            }
        }

        if(flag) break;

        hash[key].push_back(i);
    }

    if(flag) printf("Twin snowflakes found.\n");
    else printf("No two snowflakes are alike.\n");

    return 0;
}

 

posted on 2013-07-24 12:41  Still_Raining  阅读(211)  评论(0编辑  收藏  举报