hiho 1656

(构造+字典树)
题意:给定 n 个字符串 si 以及它们各自的权值 wi ,然后给出 m 个询问,每个询问包含两个字符串 s1,s2 ,求上述给定字符串中以 s1 为前缀且以 s2 为后缀的字符串中权值最大的是多少? (1n,M50000,1|si|,|s1|,|s2|101wi100000)

思路:这个题很巧妙,难点是有前缀和两个条件共同作用。而这题关键是观察到每个字符串长度都很小,并且想到先固化某一个条件的方法。观察到这个单词长度较小,于是可以拆单词,将一个单词拆成10个单词:它的第 i 个前缀连接上它的逆序列。这样把拆出来的第 i 个单词放入第 i 个字典树上,就可以构建10颗字典树,最后将每个查询连接成 s1+(s2) ,在第 |s1| 颗字典树上查询即可。

吐槽:一直用定长数组做要么RE要么TLE,于是改用指针动态分配空间的方法做就AC了,以后字典树还是用指针动态分配空间的方法比较好。

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long

using namespace std;
const double eps = 1e-8;
const int maxn = 10000;

struct node {
    int cnt;
    node *nxt[26];
    node(){ cnt = -1; for(int i=0; i<26; i++) nxt[i] = NULL; }
};

struct Trie {
    node *root;

    void init() {
        root = new node;
        for (int i = 0; i < 26; i++)
            root->nxt[i] = NULL;
    }

    void Insert(char *s, int val) {
        node *p = root;
        int len = strlen(s);
        for (int i = 0; i < len; i++) {
            int id = s[i] - 'a';
            if (p->nxt[id] == NULL) {
                node *q = new node();
                p->nxt[id] = q;
                p = p->nxt[id];
            }
            else {
                p = p->nxt[id];
            }
            p->cnt = max(p->cnt, val);
        }
    }

    int Query(char *s) {
        node *p = root;
        int len = strlen(s);
        for (int i = 0; i < len; i++) {
            int id = s[i] - 'a';
            if (p->nxt[id] == NULL) return -1;
            else {
                p = p->nxt[id];
            }
        }
        return p->cnt;
    }

    void Clear(node *p) {
        if (p == NULL) return;
        for (int i = 0; i < 26; i++) {
            if (p->nxt[i] != NULL) Clear(p->nxt[i]);
        }
        free(p);
        p = NULL;
    }
} T[12];

int main()
{
    //freopen("test.txt","r",stdin);
    int n, q;
    while(scanf("%d%d",&n,&q) == 2) {
        for(int i=0; i<11; i++)
            T[i].init();
        for(int i=0; i<n; i++) {
            int w = 0;
            char s1[30], s2[30];
            scanf("%s%d",s1,&w);
            int len = strlen(s1);
            for(int j=0; j<len; j++) {
                int k = 0;
                for(k=0; k<=j; k++) s2[k] = s1[k];
                for(k=j+1; k<j+1+len; k++) s2[k] = s1[j+len-k];
                s2[k] = '\0';
                //printf("i:%d j:%d s:%s\n",i,j,s2);
                T[j].Insert(s2, w);
            }
        }
        while(q --) {
            char pre[30], suf[30];
            scanf("%s%s",pre,suf);
            int len1 = strlen(pre), len2 = strlen(suf), k = len1;
            for(k=len1; k<len1+len2; k++) pre[k] = suf[len1+len2-1-k];
            pre[k] = '\0';
            //printf("id:%d query: %s\n",len1-1,pre);
            int ans = T[len1-1].Query(pre);
            printf("%d\n",ans);
        }
    }
    return 0;
}
发布了40 篇原创文章 · 获赞 44 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/Site1997/article/details/78795135