pku1204 Word Puzzles (Trie)

trie, 递归和非递归的查询都实现了一下

 

#include <stdio.h> #include <vector> using namespace std; char str[1010][1010]; int L, C, W; int srcx, srcy; int dir[8][2] = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}}; int loc[1001]; int count = 0; const int kind=26;//字母种类 struct Treenode//树的结点结构 { vector<int> ids;//这个附加变量在本题中记录遍历到该结点形成的字符串出现的次数,在不同题中可记录不同的内容。 Treenode *next[kind];//指向儿子结点 Treenode()//每个结点的初始化 { for(int i=0;i<kind;i++) next[i]=NULL; } }; void insert(Treenode *&root,char *word, int id)//向以root为根结点的树中插入串word { Treenode *location=root; int i=0,branch=0; if(location==NULL) {location=new Treenode();root=location;} while(word[i]) { branch=word[i]-'A'; if(!location->next[branch]) location->next[branch]=new Treenode();//如果不存在,建新结点 i++; location=location->next[branch]; } location->ids.push_back(id); } void search(Treenode* location, int x, int y, int k) { if (x<0 || x>=L || y<0 || y>=C) return; int branch = str[x][y] - 'A', curid; if (location->next[branch] == NULL) return; location = location->next[branch]; if (location->ids.size() > 0) { for (curid=0; curid<location->ids.size(); curid++) loc[location->ids[curid]] = srcx*10000 + srcy*10 + k; count += location->ids.size(); location->ids.clear(); } search(location, x+dir[k][0], y+dir[k][1], k); } int main() { char tmp[1002]; int i, j, k, x, y, branch, curid; Treenode* root = NULL, *location; freopen("data.txt", "r", stdin); scanf("%d%d%d", &L, &C, &W); for (i=0; i<L; i++) scanf("%s", str[i]); for (i=0; i<W; i++) { scanf("%s", tmp); insert(root, tmp, i); } count = 0; for (i=0; i<L; i++) for (j=0; j<C; j++) for (k=0; k<8; k++) { srcx = i; srcy = j; search(root, i, j, k); /* x = i; y = j; location = root; while (x>=0 && x<L && y>=0 && y<C) { branch = str[x][y] - 'A'; if (location->next[branch] == NULL) break; location = location->next[branch]; if (location->ids.size() > 0) { for (curid=0; curid<location->ids.size(); curid++) { loc[location->ids[curid]] = i*10000 + j*10 + k; } count += location->ids.size(); } x += dir[k][0]; y += dir[k][1]; } */ } for (i=0; i<W; i++) { printf("%d %d %c/n", loc[i]/10000, (loc[i]%10000)/10, loc[i]%10 + 'A'); } return 0; }

你可能感兴趣的:(pku1204 Word Puzzles (Trie))