题目链接:http://poj.org/problem?id=3349
题目大意:
给你n个6条边的雪花的信息,问这些雪花当中是否有相同的一对。
相同的定义是:长度相同,且符合相同的顺序(顺时针或者逆时针),比如1 2 3 4 5 6是a雪花的6边信息,那么相同的雪花共有12种情况,就是按照顺时针和逆时针和a雪花边相等且顺序相同。如顺时针可以是:2 3 4 5 6 1或者3 4 5 6 1 2。逆时针可以是6 5 4 3 2 1 或者4 3 2 1 6 5.
解题思路:
Hash的一道题,难点在于对雪花信息的处理上,就是如何判断2片雪花在顺时针和逆时针方向是否相同。剩下的就是基础的Hash知识。反正我是自己写了5、6个小时才算弄好,好在全是自己写的,很有成就感。哈哈哈哈哈哈哈
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<climits>
using namespace std;
#define CLR(arr, what) memset(arr, what, sizeof(arr))
#define MAX 100003
#define N 100010
struct snownode //结构体存放雪花信息
{
int snow[6];
int sum; //6边之和
};
bool cmp(const snownode &a, const snownode &b)
{
int k;
bool flag1, flag2;
for(int p = 0; p < 6; ++p)
{
flag1 = flag2 = true; //正向、反向
if(a.snow[p] == b.snow[0])
{
k = p; //找到相同的开头
for(int i = k, j = 0; j < 6; i = (i + 1) % 6, ++j) //正向
{
if(a.snow[i] != b .snow[j])
{
flag1 = false;
break;
}
}
if(flag1 == true)
return true;
for(int i = k, j = 0; j < 6; i = (i + 6 - 1) % 6, ++j) //反向
{
if(a.snow[i] != b .snow[j])
{
flag2 = false;
break;
}
}
if(flag2 == true)
return true;
}
}
return false;
}
template<class T>
class Hash
{
private:
int Head[N], Next[N];
snownode Key[N];
int top;
public:
void add(const snownode p);
bool search();
void init();
};
template<class T>
inline void Hash<T>::init() //初始化
{
top = 0;
CLR(Head, -1);
CLR(Next, -1);
CLR(Key, 0);
}
template<class T>
inline void Hash<T>::add(const snownode p) //雪花6个长度之和
{
int temp;
temp = p.sum % MAX;
Key[top].sum = p.sum;
Key[top].snow[0] = p.snow[0]; Key[top].snow[1] = p.snow[1]; Key[top].snow[2] = p.snow[2];
Key[top].snow[3] = p.snow[3]; Key[top].snow[4] = p.snow[4]; Key[top].snow[5] = p.snow[5];
Next[top] = Head[temp];
Head[temp] = top;
top++;
}
template<class T>
inline bool Hash<T>::search()
{
for(int i = 0; i < MAX; ++i) //总链数目
for(int j = Head[i]; j != -1; j = Next[j]) //遍历每条链
{
for(int k = Next[j]; k != -1; k = Next[k])
if(Key[j].sum == Key[k].sum && cmp(Key[j], Key[k]) == true)
return true;
}
return false;
}
Hash<int> h;
int main()
{
int snownum;
snownode p;
while(scanf("%d", &snownum) != EOF)
{
h.init();
p.sum = 0;
for(int i = 0; i < snownum; ++i)
{
for(int j = 0; j < 6; ++j) //雪花信息
{
scanf("%d", &p.snow[j]);
p.sum += p.snow[j];
}
h.add(p);
p.sum = 0;
}
if(h.search())
printf("Twin snowflakes found.\n");
else
printf("No two snowflakes are alike.\n");
}
return 0;
}