HDU 1075 What Are You Talking About (map解法+Trie解法)

来源:互联网 发布:小学生编程比赛 编辑:程序博客网 时间:2024/05/29 11:44

HDU 1075 What Are You Talking About (map解法+Trie解法)

ACM

题目地址: 
HDU 1075 What Are You Talking About

题意: 
给出一个“翻译-原文”的对应表,然后给出句子,要把句子中的原文都翻译出来。

分析: 
可以用map赤裸裸地做,但是比较花费时间,虽然这题时间给了5s,map解法是能过的。 
不过Trie解法500+ms,果然Trie字典树才是正解啊。 
Trie入门题。

另外发现ios_base::sync_with_stdio(0)这句话是关闭IO同步的,如果把cin和gets混用就不同步...坑了好久..

代码

(map解法)

/**  Author:      illuz <iilluzen[at]gmail.com>*  File:        1075_map.cpp*  Create Date: 2014-09-23 13:48:38*  Descripton:   */#include <cstdio>#include <cstring>#include <cctype>#include <map>#include <iostream>#include <algorithm>using namespace std;#define repf(i,a,b) for(int i=(a);i<=(b);i++)typedef long long ll;string a, b;char s[3010];map<string, string> mp;int main() {// ios_base::sync_with_stdio(0);cin >> a;while (cin >> a) {if (a == "END")break;cin >> b;mp[b] = a;}cin >> a;getchar();while (1) {gets(s);if (!strcmp(s, "END"))break;int len = strlen(s);a = "";repf (i, 0, len - 1) {if (islower(s[i])) {a += s[i];} else {if (mp.find(a) != mp.end())cout << mp[a];elsecout << a;a = "";cout << s[i];}}cout << endl;}return 0;}


(Trie解法)

/**  Author:      illuz <iilluzen[at]gmail.com>*  File:        1075_trie.cpp*  Create Date: 2014-09-23 14:25:31*  Descripton:  trie*/#include <cstdio>#include <cstring>#include <cctype>#include <iostream>#include <algorithm>using namespace std;#define repf(i,a,b) for(int i=(a);i<=(b);i++)typedef long long ll;const int N = 3010;const int SIZE = 26;// pointer triestruct Node {char* val;Node *next[SIZE];};struct PTrie {Node *root;PTrie() { root = newNode(); }void init() { del(root); root = newNode(); }inline int idx(char c) { return c - 'a'; }Node *newNode() {Node *u = new Node;repf (i, 0, SIZE - 1) {u->next[i] = NULL;}u->val = NULL;return u;}void insert(char *s, char *v) {Node *u = root;int len = strlen(s);repf (i, 0, len - 1) {int c = idx(s[i]);if (u->next[c] == NULL)u->next[c] = newNode();u = u->next[c];}u->val = new char[11];strcpy(u->val, v);}void find(char *s) {Node*u = root;int len = strlen(s);repf (i, 0, len - 1) {int c = idx(s[i]);if (u->next[c] == NULL) {printf("%s", s);return;}u = u->next[c];}if (u->val)printf("%s", u->val);elseprintf("%s", s);}void del(Node *rt) {if (rt == NULL)return;else {repf (i, 0, SIZE - 1)if (rt->next[i])del(rt->next[i]);}delete rt->val;delete rt;}} trie;char a[11], b[11];char str[N], rec[N];int main() {// ios_base::sync_with_stdio(0);scanf("%s", a);while (scanf("%s %s\n", a, b) && strcmp(a, "END")) {//cout << a << b << endl;trie.insert(b, a);}while (gets(str) && strcmp(str, "END")) {int len = strlen(str);int idx = 0;repf (i, 0, len - 1) {if (islower(str[i])) {rec[idx++] = str[i];} else {rec[idx] = 0;trie.find(rec);idx = 0;printf("%c", str[i]);}}puts("");}}



0 0