POJ 3349 哈希一维搜索降二维
Time Limit: 4000MS | Memory Limit: 65536K | |
Total Submissions: 41141 | Accepted: 10817 |
Description
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.
Input
The first line of input 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.
Output
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.
Sample Input
2 1 2 3 4 5 6 4 3 2 1 6 5
Sample Output
Twin snowflakes found.
题意:n个雪花,每个雪花6个花瓣,给定每个花瓣的大小,给定的大小是从任意一片逆时针或者顺时针数的,判断是否有两片相同的,有后面就不用判断
思路:一维搜索的话肯定是n^2级,而且会有超时的风险,这题摆明了就是优化查找时间复杂度。这里把每个花瓣长度和为一个集合,相同则查找这个集合的每一个花瓣。然后就是取模,进制的大小直接决定时间和内存,所以这里可以在内存消耗和时间消耗上之间转换,开始取模20000,现在取模11000,那么相加sum%10000的键值肯定增多了,snow[][]的第二维有所增大,所以膜取大小除了看题意,还要看限制的时间和内存
#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int ssum = 11000+1000; const int nnum = 100;//相等的数量有多少个 const int nn = 7; //当前和值,当前和值的数量,花瓣的数量 struct Node { int a[6]; }snow[ssum][nnum],t; int num[ssum];///ssum是相等的数量值,一开始开了nnum,肯定不够,随便加起来就爆了,这个数组大小外界是存的是相加起来的值,取模了之后肯定比进制小 int base = 11000; int getHash(Node t) { int sum = 0; for(int i = 0; i < 6; i++) { sum += t.a[i]; } sum %= base; return sum; } int cmp(Node str,Node sub) { int j,pos; for(int i = 0; i < 6; i++) { for(j = 0,pos = i; j < 6; j++,pos=(pos+1)%6) {//下一个,右移 if(str.a[j]!=sub.a[pos]) break; } if(j==6) return 1; } for(int i = 0; i < 6; i++) { for(j = 0,pos = i; j < 6; j++,pos=(pos+5)%6) {//总数量5,也就是后退一位 if(str.a[j]!=sub.a[pos]) break; } if(j==6) return 1; } return 0; } int main() { // freopen("in.txt","r",stdin); int n,cur; cin>>n; for(int i = 0; i < n; i++) { for(int j = 0; j < 6; j++) { scanf("%d",&t.a[j]); } cur = getHash(t); for(int k = 0; k < num[cur]; k++) { if(cmp(t,snow[cur][k])) { puts("Twin snowflakes found."); return 0; } } //没有找到,当前cur++ snow[cur][num[cur]] = t;//把当前插入存储 num[cur]++; } puts("No two snowflakes are alike."); return 0; }