您的位置:首页 > 其它

NYOJ 题目130 相同的雪花 (哈希表)

2016-03-31 17:50 417 查看


相同的雪花

时间限制:1000 ms  |  内存限制:65535 KB
难度:4

描述You may have heard that no two snowflakes are alike. Your task is to write a program to determine whether this is really true. Your
program will read information about a collection of snowflakes, and search for a pair that may be identical. Each snowflake has six arms. For each snowflake, your program will be provided with a measurement of the length of each of the six arms. Any pair of
snowflakes which have the same lengths of corresponding arms should be flagged by your program as possibly identical.

输入The first line of the input will contain a single interger T(0<T<10),the number of the test cases.

The first line of every test case will contain a single integer n, 0 < n ≤ 100000, the number of snowflakes to follow. This will be followed by n lines, each describing a snowflake. Each snowflake will be described by a line containing six integers (each integer
is at least 0 and less than 10000000), the lengths of the arms of the snow ake. The lengths of the arms will be given in order around the snowflake (either clockwise or counterclockwise), but they may begin with any of the six arms. For example, the same snowflake
could be described as 1 2 3 4 5 6 or 4 3 2 1 6 5.
输出For each test case,if all of the snowflakes are distinct, your program should print the message:

No two snowflakes are alike.

If there is a pair of possibly identical snow akes, your program should print the message:

Twin snowflakes found.
样例输入
1
2
1 2 3 4 5 6
4 3 2 1 6 5


样例输出
Twin snowflakes found.


题意:给出若干行每行6个数字,判断这六个数字是否相同并且将六个数字绕成环后是一个相同的环。

思路:把6个数字求和,因为和太大,所以用和对一个较大的数字取余,取余后的数作为哈希表的KEY。每次输入一个数,求出该数对应的KEY,然后去哈希表中找,若有相同的,则flag=1。

代码如下:#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#define N 100007
using namespace std;
typedef struct {
int a[6];
int sum;
}node;
vector<node> v
;//用不定长数组做哈希表
bool cmp(node x,node y){
int i;
int t[12];
if(x.sum != y.sum)return 0;//如果合不一样,即冲突,就返回0
for(i=0;i<6;i++){
t[i]=x.a[i];
t[i+6]=x.a[i];
}
for(i=0;i<6;i++){//顺方向判断
if(t[i]==y.a[0]&&t[i+1]==y.a[1]&&t[i+2]==y.a[2]&&t[i+3]==y.a[3]&&t[i+4]==y.a[4]&&t[i+5]==y.a[5])
return 1;
}
for(i=11;i>5;i--){//反方向判断
if(t[i]==y.a[0]&&t[i-1]==y.a[1]&&t[i-2]==y.a[2]&&t[i-3]==y.a[3]&&t[i-4]==y.a[4]&&t[i-5]==y.a[5])
return 1;
}
return 0;
}
int main(){
int cases,i,j,n,flag;
cin>>cases;
while(cases--){
flag=0;
for(i=0;i<=N;i++)
v[i].clear();//初始化
cin>>n;
for(i=1;i<=n;i++){
node temp;
scanf("%d%d%d%d%d%d",&temp.a[0],&temp.a[1],&temp.a[2],&temp.a[3],&temp.a[4],&temp.a[5]);
temp.sum = temp.a[0]+temp.a[1]+temp.a[2]+temp.a[3]+temp.a[4]+temp.a[5];
for(j=0;j<v[temp.sum%N].size();j++){
if( cmp(v[temp.sum%N][j] , temp) ){//判断哈希表中是否有一样的雪花
flag=1;
break;
}
}
if(flag==0){//如果没有,加入对应的哈希表
v[temp.sum%N].push_back(temp);
}
}
if(flag)cout<<"Twin snowflakes found."<<endl;
else cout<<"No two snowflakes are alike."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  哈希表