题目链接:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1642 分析:在Trie结构中加一个dp数组就好了,表示每一个Trie结点对应每一个表格中字母的状态。 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define mp make_pair #define X first #define Y second #define MEMSET(a, b) memset(a, b, sizeof(a)) using namespace std; typedef unsigned int ui; typedef long long ll; typedef unsigned long long ull; typedef pair pii; typedef vector vi; typedef vi::iterator vi_it; typedef map mii; typedef priority_queue pqi; typedef priority_queue , greater > rpqi; typedef priority_queue pqp; typedef priority_queue , greater > rpqp; char grid[35][35]; int h, w; struct trie { trie *child[26]; bool isWord; int coll[30][30]; } *root; trie* new_node() { trie *p = new trie(); p->isWord = false; for (int i = 0; i < 26; ++i) { p->child[i] = NULL; } MEMSET(p->coll, 0); return p; } void ins(char *s) { char *p = s; trie *q = root; while (*p) { if (q->child[*p - 'A'] == NULL) { q->child[*p - 'A'] = new_node(); } q = q->child[*p++ - 'A']; } q->isWord = true; } int solve(int x, int y, trie *head) { int tmp = head->coll[x][y]; if (tmp) { return tmp; } int idx = grid[x][y] - 'A'; trie *p = head; head = head->child[idx]; tmp += head->isWord; for (int i = x; i < h; ++i) { for (int j = y; j < w; ++j) { if (i == x && j == y) { continue; } if (head->child[grid[i][j] - 'A'] != NULL) { tmp += solve(i, j, head); } } } return p->coll[x][y] = tmp; } int main(int argc, char *argv[]) { // freopen("D:\\in.txt", "r", stdin); char str[35]; int i, j; scanf("%d%d\n", &h, &w); for (i = h - 1; i >= 0; --i) { gets(grid[i]); } gets(str); root = new_node(); while (gets(str)) { ins(str); } int ans = 0; for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) { if (root->child[grid[i][j] - 'A'] != NULL) { ans += solve(i, j, root); } } } printf("%d\n", ans); return 0; }