Library management through a string

Title Description

Library management is a very complex work, in a library, there will be many new books added every day. In order to facilitate the management books (for guests who want to quickly find to help if they have a library of books they need), we need to design a system to find books.

The system needs to support two modes of operation:

add (s) represent a new book added to the book called s.
find (s) indicates that the query whether there is a book called the Book of s.

Input Format

The first line includes a positive integer operands. The following lines of a given article 2 operating instruction in the instruction format is:

s the Add
Find s
between s title and command (add, find) has a spaced apart, we ensure that no more than the length of all titles. It can be assumed that the data read is accurate.

Output Format

For each find (s) command, we have a corresponding output line of yes or no, the book represents the current query exists in the library.

Note: When you start the library is not a book. And, for different case letters of the same title, we think they are different.

Sample

Sample input

4
add Inside C#
find Effective Java
add Effective Java
find Effective Java

Sample Output

no
yes

Data range and tips

n <= 30000。

Thinking

Two hash values ​​generated string, a hash value determination head of the list, another hash value determines a position behind the head of a linked list.

Code

#include <cstdio>
#include <cstring>
#include <cmath>
int n;
char a[10], b[209];
int bs = 37, h1 = 90001, h2 = 90007;
int head[90001], nxt[30005], ver[30005], ht;
int res1, res2, len;

bool find(int x, int y) {
    for (int i = head[x]; i; i = nxt[i]) {
        if (ver[i] == y) return true;
    }
    return false;
}

void add(int x, int y) {
    if (!find(x, y)) {
        nxt[++ht] = head[x];
        ver[ht] = y;
        head[x] = ht;
    }
}


int main() {
    // 产生哈希表的两个数
    // int cnt = 0;
    // for (int i = 90001; cnt < 2; i += 2) {
        // bool flag = false;
        // for (int j = 3; j <= sqrt(i); ++j) {
            // if (i % j == 0) flag = true;
        // }
        // if (!flag) {
            // printf("%d\n", i);
            // cnt++;
        // }
    // }
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        scanf("%s", a);
        gets(b + 1);
        len = strlen(b + 1);
        res1 = 0, res2 = 0;
        for (int i = 1; i <= len; ++i) {
            res1 = ((long long)res1 * bs % 90001 + b[i]) % 90001;
            res2 = ((long long)res2 * bs % 90007 + b[i]) % 90007;
        }
        if (strcmp(a, "add") == 0) {
            add(res1, res2);
        } else {
            if (find(res1, res2)) puts("yes");
            else puts("no");
        }
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/liuzz-20180701/p/11484283.html