(Tree structure + dictionary)
meaning of the questions: Given
Ideas: This title is very clever, difficulty is there are two conditions prefix and interaction. This problem is observed in each of the key string length is very small, and one conceivable method to curing conditions. The observed small length word, the word can then be removed, one word is split into 10 words: its first
Tucao: has to do with the fixed-length array or RE or TLE, then switch method for dynamic allocation of space to do on AC pointer, and after a trie pointer or dynamically allocated space approach is better.
Code:
#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;
}