POJ 3349 Snowflake Snow Snowflakes (哈希表)

题目链接:http://poj.org/problem?id=3349


题意:给出n个6的数字的数字串,判断是否有两个数字串相等(两个数字串相等的条件是两个数字串排好序后各个数字相等,仅此而已,别想多了)


思路:用结构体存放每一个数字串。但因为数目较大,用map或set都会超时,所以改用哈希表的方法存储。


#include<cstdio>
#include<cstring>
#include<vector>
#include<set>
#include<queue>
#include<map>
#include<iostream>
#include<cmath>
#include<stack>
#include<cctype>
#include<algorithm>
using namespace std;
typedef pair<int, int> P;
typedef long long ll;
const int maxnode = 100007;

struct Node {
  int a[6];
  bool operator == (const Node& rhs) const {
    for(int i = 0; i < 6; i++)
      if(a[i] != rhs.a[i]) return false;
    return true;
  }
}web[maxnode];

int a[6];
int head[maxnode], next[maxnode];

int get_hash(Node& node) {
  int sum = 0;
  for(int i = 0; i < 6; i++) {
    sum += node.a[i];
  }
  return sum %= maxnode;
}

bool Insert(int id) {
  int h = get_hash(web[id]);
  int u = head[h];
  while(u) {
    if(web[u] == web[id]) return false;
    u = next[u];
  }
  next[id] = head[h];
  head[h] = id;
  return true;
}

int main() {
  int n, cur = 0;
  bool ok = false;
  scanf("%d", &n);

  while(n--) {
    ++cur;
    for(int i = 0; i < 6; i++) {
      scanf("%d", &web[cur].a[i]);
    }
    sort(web[cur].a, web[cur].a+6);
    if(!Insert(cur)) {
      ok = true;
      break;
    }
  }

  if(ok) printf("Twin snowflakes found.\n");
  else printf("No two snowflakes are alike.\n");
  return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值