小记:这题练的是对Trie树的运用,对火星文字符串建树,每个火星单词标记它为对应英文单词。这题就是对Trie节点多添加一个信息,然后是字符串的处理,练你码字的能力和基础了。1A,很幸运。 这题因为只有一个测试用例 所以可以不释放开辟的空间,因此速度会快点,我不释放是250MS,释放是300多MS。
贴上释放代码:
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std; #define MAX 26 typedef struct Node{ int isStr; char s[10]; struct Node *next[MAX]; Node():isStr(0){ memset(s,0,sizeof(s)); memset(next, NULL, sizeof(next)); } ~Node(){ for(int i = 0;i < MAX; ++i) if(next[i] != NULL) delete next[i]; } }TrieNode,*Trie; Trie root; char s1[3001]; void Insert(char *s,char *str){ TrieNode *p = root; while(*s){ if(p ->next[*s-'a'] == NULL){ p ->next[*s-'a'] = new TrieNode; } p = p ->next[*s-'a']; s++; } p->isStr = 1; strcpy(p->s,str); return ; } int find(char *s){ TrieNode *p = root; while(*s){ if(p->next[*s - 'a'] != NULL){ p = p->next[*s - 'a']; s++; } else return 0; } if(p->isStr){ printf("%s",p->s); return 1; } return 0; } int main() { //freopen("f:\\in1.txt","r",stdin); //freopen("f:\\out1.txt","w",stdout); int num = 0, k, i, j, flag, len; char s2[10], c; root = new TrieNode; scanf("%s",s2); while(scanf("%s",s2)){ if(s2[0] == 'E')break; scanf("%s",s1); Insert(s1,s2); } scanf("%s",s1); getchar(); while(gets(s1)){ if(s1[0] == 'E')break; len = strlen(s1); for(int i = 0; i < len; i++){ if(s1[i] >= 'a' && s1[i] <= 'z'){ s2[num++] = s1[i]; } else { s2[num] = '\0'; if(!find(s2)) printf("%s",s2); num = 0 ; printf("%c",s1[i]); } } putchar('\n'); } delete root; }
2014.4.29 (ss数组必须开到这么大)
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <map> #include <set> #include <vector> #include <stack> #include <queue> #include <algorithm> using namespace std; #define mst(a,b) memset(a,b,sizeof(a)) #define eps 10e-8 const int MAX_ = 3010; const int MAX = 26; const int N = 500010; const int INF = 0x7fffffff; typedef struct Node{ int isStr; struct Node *next[MAX]; Node():isStr(-1){ memset(next, NULL, sizeof(next)); } ~Node(){ for(int i = 0;i < MAX; ++i) if(next[i] != NULL) delete next[i]; } }TrieNode,*Trie; Trie root; char s[MAX_], str[MAX_], ss[N][15]; void Insert(char *s, int num){ TrieNode *p = root; while(*s){ if(p ->next[*s-'a'] == NULL){ p ->next[*s-'a'] = new TrieNode; } p = p ->next[*s-'a']; s++; } p->isStr = num; } int find(char *s){ int i = 0; TrieNode *p=root; while(*s){ if(p->next[*s-'a'] == NULL)return -1; p = p->next[*s-'a']; s++; } return p->isStr; } int main() { int ans, cnt, len, T, n; cnt = 0; root = new TrieNode; scanf("%s",s); while(scanf("%s",s) && s[0] != 'E'){ scanf("%s",str); strcpy(ss[cnt], s); Insert(str, cnt);cnt++; } scanf("%s",s); getchar(); cnt = 0; while(gets(s)&& s[0] != 'E'){ len = strlen(s); for(int i = 0; i < len; ++i){ if(s[i] >= 'a' && s[i] <= 'z'){ str[cnt++] = s[i]; } else { str[cnt] = '\0'; n = find(str); if(n == -1){ printf("%s", str); } else printf("%s", ss[n]); cnt = 0; printf("%c", s[i]); } } putchar('\n'); } delete root; }