Codeforces 861 D Polycarp's phone book(字典树模板)

来源:互联网 发布:mac os清理软件 编辑:程序博客网 时间:2024/06/10 03:00

题目地址
题意:给你n个电话号码,请你尽可能得缩短每一个电话号码,使得缩短后的每个字符串能代表该电话号码(就是缩短后的字符串不能是多个电话号码的子串)
思路:把所有的电话号码的后缀全部存入字典树然后我们通过标记这个子串出现过几次,最后通过搜索把所有标记为一的放入map中去比较,当长度更短或者原来没有出现的话就更新map。
附加:我对与更新后缀对同一电话号码的子串不需要重复加一的操作就是每次还要跟新这个子串所在的最新电话号码是什么,如果是相同的就不用对num++了。

#include <iostream>#include <cstring>#include <string>#include <queue>#include <vector>#include <map>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <algorithm>#define N 200010#define LL __int64#define inf 0x3f3f3f3f#define lson l,mid,ans<<1#define rson mid+1,r,ans<<1|1#define getMid (l+r)>>1#define movel ans<<1#define mover ans<<1|1using namespace std;struct node {    node *next[10];    int ans, num;    void init() {        for (int i = 0; i < 10; i++) {            next[i] = NULL;        }        num = 0;        ans = -1;    }}root;map<int, string> mapp;void Free(node *p) {    for (int i = 0; i<10; ++i)if (p->next[i])Free(p->next[i]);    delete p;}void dfs(string str, node *p) {    if (p->num == 1) {        if (mapp.find(p->ans) == mapp.end() || str.length() < mapp[p->ans].length()) {            mapp[p->ans] = str;        }        return;    }    for (int i = 0; i < 10; i++) {        if (p->next[i] != NULL) {            dfs(str + (char)(i + '0'), p->next[i]);        }    }}int main() {    cin.sync_with_stdio(false);    int n;    node *p;    string str;    while (cin >> n) {        root.init();        for (int T = 1; T <= n; T++) {            cin >> str;            for (int j = 0; j < str.length(); j++) {                p = &root;                for (int i = 0; i < str.length(); i++) {                    int k = str[i] - '0';                    if (p->next[k] == NULL) {                        p->next[k] = new node;                        p->next[k]->init();                    }                    p = p->next[k];                    if(p->ans!=T) p->num++;                    p->ans = T;                }            }        }        mapp.clear();        p = &root;        dfs("", p);        for (int i = 1; i <= n; i++) {            cout << mapp[i] << endl;        }        for (int i = 0; i<10; ++i) {            if (root.next[i])Free(root.next[i]);            root.next[i] = NULL;        }    }    return 0;}
阅读全文
0 0
原创粉丝点击