poj2002 简单哈希表的运用

题意:给定n个相异整数点,求能构成多少个正方形。
其实这题挺简单的,经过思考可以发现,我们可以通过枚举两个点(或者说一条边),然后求出可能构成正方形的另外两个点,然后判断是不是在给你的点集中就行了。求点问题是一个数学问题,判断要用到hash表。本来很简单的问题,由于对数学的菜,所以是2Y,第一次WA了,主要原因是在构造四边形的时候出问题了。
我对这个问题做了分析,在本题后面的 disuss里面。希望有帮助。
代码
 
    
1 #include < stdio.h >
2 #include < string .h >
3 #include < iostream >
4   using namespace std;
5 #define MAXHASH 1000003
6 #define NN 1004
7 typedef struct node{
8 int x, y;
9 struct node * nxt;
10 }NODE;
11
12 NODE po[NN];
13 NODE * head[MAXHASH];
14 int n;
15
16 int hash(NODE p){
17 int h = p.x * 20000 + p.y;
18 h %= MAXHASH;
19 if (h < 0 ) h += MAXHASH;
20 return h;
21 }
22 void Init(){
23 int i, h;
24 memset(head, 0 , sizeof (head));
25 for (i = 1 ; i <= n; i ++ ){
26 h = hash(po[i]);
27 po[i].nxt = head[h];
28 head[h] = po + i;
29 }
30 }
31
32 int find(NODE p1){
33 int h = hash(p1);
34 for (NODE * p = head[h]; p; p = p -> nxt){
35 if (p -> x == p1.x && p -> y == p1.y){
36 return 1 ;
37 }
38 }
39 return 0 ;
40 }
41 void Solve(){
42
43 NODE p1, p2, p3, p4;
44 int i, j;
45 int cnt = 0 ;
46 for (i = 1 ; i <= n; i ++ ){
47 for (j = 1 ; j <= n; j ++ ){
48 if (i == j) continue ;
49 // 公式:x3=x1+(y1-y2);y3=y1-(x1-x2); x4=x2+(y1-y2);y4=y2-(x1-x2)(在直线AB上方)
50 // 或x3=x1-(y1-y2);y3=y1+(x1-x2); x4=x2-(y1-y2);y4=y2+(x1-x2)(在直线AB下方)
51 p1 = po[i];
52 p2 = po[j];
53 p3.x = p1.x + (p1.y - p2.y);
54 p3.y = p1.y - (p1.x - p2.x);
55 p4.x = p2.x + (p1.y - p2.y);
56 p4.y = p2.y - (p1.x - p2.x);
57
58 if (find(p3) && find(p4)) cnt ++ ;
59 }
60 }
61 printf( " %d\n " , cnt / 4 );
62 }
63 int main() {
64 int i;
65 while (scanf( " %d " , & n) != EOF){
66 if (n == 0 ) break ;
67 for (i = 1 ; i <= n; i ++ ){
68 scanf( " %d%d " , & po[i].x, & po[i].y);
69 }
70 Init();
71 Solve();
72 }
73 return 0 ;
74 }
75

参考:

转载于:https://www.cnblogs.com/ylfdrib/archive/2010/12/07/1898873.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值