P1184 高手之在一起(字典树模板题,hash算法, map)

哎,唯一值得说明的是,这道题的输入有bug

先把字典树的算法模板放一下

#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 26;
struct node{
    int num;
    node *next[maxn];
};
//字典树
class Tree{
public:
    node *head;
    Tree(){
        head = New();
    }
    node* New(){
        node *p = new node();
        for (int i = 0; i < maxn; ++i)
        {
            p->next[i] = NULL;
        }
        p->num = 0;
        return p;
    }
    void insert(char *str)
    {
        int len = strlen(str);
        node *t, *p = head;
        for (int i = 0; i < len; ++i)
        {
            int c = str[i] - 'a';
            if (p->next[c] == NULL){
                t = New();        //构建新的节点
                p->next[c] = t;
            }
            p = p->next[c];
            p->num++;
        }
    }
    int find(char *str){
        node *p = head;
        int len = strlen(str);
        for (int i = 0; i < len; ++i)
        {
            int c = str[i] - 'a';
            if (p->next[c] == NULL)
                return 0;
            p = p->next[c];
        }
        return p->num;
    }
};

这是我得代码:

map真香

#include<iostream>
#include<map>
#include<cstdio>
#include<string>
using namespace std;
map<string, int>kap;
string num;
int n, m;
int ans;
int main(){
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
    {
        cin >> num;
        while (getchar() == ' '){
            string s;
            cin >> s;
            num += s;
        }
        kap[num] = 1;
    }
    for (int i = 0; i < m; ++i)
    {
        cin >> num;
        while (getchar() == ' '){
            string s;
            cin >> s;
            num += s;
        }
        if (kap.find(num) != kap.end())ans++;
    }
    cout << ans << endl;
}
原文地址:https://www.cnblogs.com/ALINGMAOMAO/p/10380527.html