题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1457
读了一遍题想到了字典树,但不知道怎么写,队友一个单词一个单词的枚举,然后暴搜过了,赛后查题解发现就是字典树+暴搜,比队友写的少了几百毫秒
#include <bits/stdc++.h>
using namespace std;
int trie_n;
const int MAXN = 400006;
char mat[5][5];
bool vis[5][5],book[MAXN];
int to[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{1,1},{1,-1},{-1,-1},{-1,1}};
int point[] = {0,0,0,1,1,2,3,5,11,11,11};
struct Trie_node
{
int next[26];
int index,val;
Trie_node()
{
index = val = -1;
fill(next,next + 26,-1);
}
};
char temp[10];
Trie_node trie[MAXN];
int ans1,ans2;
char word[15];
void trie_insert(char s[],int index)
{
int root = 0;
int len = strlen(s);
for(int i = 0; i < len; i++) {
int next = trie[root].next[s[i] - 'A'];
if(next == -1) {
next = trie[root].next[s[i] - 'A'] = trie_n++;
}
root = next;
}
trie[root].index = index;
trie[root].val = point[len];
}
void solve(char *s)
{
int root = 0;
int len = strlen(s);
for(int i = 0; i < len; i++) {
int next = trie[root].next[s[i] - 'A'];
if(next == -1) break;
root = next;
}
if(trie[root].val != -1 && !book[trie[root].index]) {
book[trie[root].index] = 1;
ans1++;
ans2 += trie[root].val;
if(ans1 == 1) memcpy(word,s,10);
else if(len == strlen(word) && strcmp(s,word) < 0)
memcpy(word,s,10);
else if(len > strlen(word))
memcpy(word,s,10);
}
}
void dfs(int x,int y,int cur)
{
if(cur > 8) return;
temp[cur - 1] = mat[x][y];
temp[cur] = '\0';
solve(temp);
vis[x][y] = 1;
for(int i = 0; i < 8; i++) {
int tx = x + to[i][0];
int ty = y + to[i][1];
if(tx < 0 || ty < 0 || tx >= 4 || ty >= 4) continue;
if(vis[tx][ty]) continue;
vis[tx][ty] = 1;
dfs(tx,ty,cur + 1);
vis[tx][ty] = 0;
}
vis[x][y] = 0;
}
int main(void)
{
int n;
char str[20];
scanf("%d",&n);
trie_n = 1;
for(int i = 1; i <= n; i++) {
scanf("%s",str);
trie_insert(str,i);
}
int q;
scanf("%d",&q);
while(q--) {
ans1 = ans2 = 0;
memset(book,false,sizeof(book));
for(int i = 0; i < 4; i++) scanf("%s",mat[i]);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
dfs(i,j,1);
}
}
printf("%d %s %d\n",ans2,word,ans1);
}
return 0;
}