Problem 1011

DT,用递归做了,如果数据量更大的话应该递推。

 

 

#include #include #include #define VALID "Valid/n" #define INVALID "Invalid/n" #define NONE 0 #define NODE 1 #define LEAF 2 #define LEFTCHILD(n) (((n) << 1) + 1) #define RIGHTCHILD(n) (LEFTCHILD(n) + 1) #define STAR ((int)('*' - 'a')) struct Transition { int left, right; struct Transition* next; }; int m, n, k; int level = 0; Transition trans[15][10]; int tree[2048]; bool acceptable(const Transition* t) { return t->left >= (n - m) && t->right >= (n - m); } int getNodeType(int node) { int max = (1 << (level + 1)) - 1; if (node < 0 || node >= max || tree[node] == STAR) return NONE; else { if (getNodeType(LEFTCHILD(node)) == NONE && getNodeType(RIGHTCHILD(node)) == NONE) return LEAF; else return NODE; } } Transition *createTransition() { Transition *pts = (Transition*)malloc(sizeof(Transition)); pts->next = NULL; return pts; } bool valid(int root, int signal) { int nodeType = getNodeType(root); if (nodeType == NODE) { int left = LEFTCHILD(root); int right = RIGHTCHILD(root); Transition *pts = &trans[signal][tree[root]]; while(pts != NULL) { if (valid(left, pts->left) && valid(right, pts->right)) return true; pts = pts->next; } return false; } else if (nodeType == LEAF) { Transition *pts = &trans[signal][tree[root]]; while(pts != NULL) { if (acceptable(pts)) return true; pts = pts->next; } return false; } else return false; } void solve() { int len = n * k; for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { Transition* pts = &trans[i][j]; while (true) { scanf("%d %d", &pts->left, &pts->right); char c = getchar(); if (c == '/n') { pts->next = NULL; break; } else { pts->next = createTransition(); pts = pts->next; } } } } // while(scanf("%d/n", &level) != EOF && level != -1) { int k = 0; for (int i = 0; i <= level; i++) { for (int j = 0; j < (1 << i); j++) { char c; scanf("%c", &c); tree[k++] = (int)(c - 'a'); getchar(); } } if (n <= m)//Always valid when all the signals are acceptable. { printf(VALID); } else { if (valid(0, 0)) printf(VALID); else printf(INVALID); } } //clear for (int i = 0; i < n; i++) for (int j = 0; j < k; j++) { Transition *pts = (&trans[i][j])->next; //Transition *pnext = pts->next; while(pts != NULL) { Transition *p = pts; pts = pts->next; free(p); } } } int main() { #ifndef ONLINE_JUDGE freopen("data.txt", "r", stdin); #endif int cnt = 0; while(scanf("%d %d %d/n", &n, &m, &k) != EOF && !(n == 0 && m == 0 && k == 0)) { if (cnt > 0) printf("/n"); printf("NTA%d:/n", ++cnt); solve(); } #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; }

你可能感兴趣的:(ZOJ,Problem)