POJ 3274 Gold Balanced Lineup 哈希

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

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <algorithm>
 4 
 5 bool feature[100001][30];
 6 int sum[100001][30], c[100001][30], n, k;
 7 const int prime = 99991;
 8 
 9 struct hash_table
10 {
11     int flag;
12     struct hash_table *next;
13 }*Hash[prime];
14 
15 int hash_insert(int key, int flag)
16 {
17     if(Hash[key] == NULL)
18     {
19         Hash[key] = new hash_table;
20         Hash[key]->flag = flag;
21         Hash[key]->next = NULL;
22         return 0;
23     }
24     struct hash_table *p = Hash[key];
25     while(p->next != NULL)
26     {
27         bool ok = 1;
28         for(int i = 0; i < k; i++)
29         {
30             if(c[p->flag][i] != c[flag][i])
31             {
32                 ok = 0;
33                 break;
34             }
35         }
36         if(ok)return flag - p->flag;
37         p = p->next;
38     }
39     for(int i = 0; i < k; i++)
40     {
41         if(c[p->flag][i] != c[flag][i])
42         {
43             p->next = new hash_table;
44             p->next->flag = flag;
45             p->next->next = NULL;
46             return 0;
47         }
48     }
49     return flag - p->flag;
50 }
51 
52 int main()
53 {
54     int x;
55     while(scanf("%d %d", &n, &k) != EOF)
56     {
57         memset(Hash, 0, sizeof(Hash));
58         for(int i = 1; i <= n; i++)
59         {
60             scanf("%d", &x);
61             for(int j = 0; j < k; j++)
62                 feature[i][j] = (x >> j) & 1;
63         }
64         memset(sum[0], 0, sizeof(sum[0]));
65         memset(feature[0], 0, sizeof(feature[0]));
66         int ans = 0;
67         hash_insert(0, 0);
68         for(int i = 1; i <= n; i++)
69         {
70             int key = 0;
71             for(int j = 0; j < k; j++)
72             {
73                 sum[i][j] = sum[i-1][j] + feature[i][j];
74                 c[i][j] = sum[i][j] - sum[i][0];
75                 key += c[i][j] * j;
76             }
77             ans = std::max(ans, hash_insert(std::abs(key)%prime, i));
78         }
79         printf("%d\n", ans);
80     }
81     return 0;
82 }
View Code

 

posted @ 2013-08-15 18:06  Anti-Magic  阅读(213)  评论(0编辑  收藏  举报