HDU - 1800 字符串哈希

题意:

从n个数中,最少能分出几个单调递增序列。


思路:

水题。就是找到n个数中出现次数最多的次数。
只是n个数范围有30个十进制位,需要当成字符串处理,这就用到了字符串哈希。


代码:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 3005;
const int MOD = 100007;

struct Node {
    Node* nxt;      // 后继指针
    char str[100];   // 保存字符串
};

struct StrHash {

    Node Hash[MAXN], *head[MOD], *cur;      // head数组记录同一哈希值的字符串的地址链表

    void init() {
        cur = Hash;
        memset(head, 0, sizeof(head));
    }

    unsigned int BKDHash(char* s) {         // 计算哈希值
        unsigned int seed = 131, res = 0;
        while (*s) res = res * seed + *s++;
        return (res & 0x7FFFFFFF) % MOD;
    }

    int getId(char* s) {                    // 从0开始依次将字符串插入hash数组,并计算哈希值,维护head链表
        int code = BKDHash(s);
        Node* ptr = head[code];
        while (ptr) {
            if (strcmp(ptr->str, s) == 0)
                return ptr - Hash;
            else ptr = ptr->nxt;
        }
        strcpy(cur->str, s);
        cur->nxt = head[code];
        head[code] = cur++;
        return cur - Hash - 1;
    }

    int Find(char* s) {         // 通过s的哈希值,找到head链表首部。然后遍历链表找到字符串在hash数组中的位置
        int code = BKDHash(s);
        Node* ptr = head[code];
        while (ptr) {
            if (strcmp(ptr->str, s) == 0)
                return ptr - Hash;
            else ptr = ptr->nxt;
        }
        return -1;
    }

} strhash;


char s[100];
int cnt[MAXN];

int main() {
    //freopen("in.txt", "r", stdin);
    int n;
    while (scanf("%d", &n) != EOF) {
        int ans = 0;
        strhash.init();
        memset(cnt, 0, sizeof(cnt));
        for (int i = 1; i <= n; i++) {
            scanf("%s", s);
            char *p = s;
            while (*p == '0') ++p;
            int id = strhash.getId(p);
            ans = max(ans, ++cn
t[id]);
        }
        printf("%d\n", ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值