您的位置:首页 > 其它

HDOJ 1075 (What Are You Talking About)

2012-06-25 10:57 337 查看
点击打开链接 http://acm.hdu.edu.cn/showproblem.php?pid=1075
思路:利用字典树+map ,但是也可以直接利用map来写,用string不要用char

注意:这组数据

START

dog aa

END

START

a aa

END

输出:a dog

代码(字典树+map):

#include <iostream>

#include <cstdio>

#include <cstring>

#include <string>

#include <cstdlib>

#include <map>

using namespace std;

string str1 , str2;

//字典树的结构体

struct node{

struct node *child[26];

int num;

};

node *root;

//创建字典树

void Tree_Insert(string str){

int i , j;

node *t , *s = root;

int len = str.size();

for(i = 0 ; i < len ; i++){

int id = str[i] - 'a';

if(s -> child[id] == 0){

t = new node;

for(j = 0 ; j < 26 ;j++)

t -> child[j] = 0;

t-> num = 0;

s -> child[id] = t;

}

s = s -> child[id];

s -> num++;

}

}

//查找单词

int Tree_search(string str){

node *t , *s = root;

int i , j;

int count;

int len = str.size();

for(i = 0 ; i < len ; i++){

int id = str[i] - 'a';

if(s -> child[id] == 0){

count = 0;

return count;

}

else{

s = s -> child[id];

count = s->num;

}

}

//以下注意判断是否存在儿子节点,要最后没有儿子节点才能够返回1

for(i = 0 ; i < 26 ; i++){

if(s -> child[i]){

count = 0;

break;

}

}

if(i == 26)

count = 1;

return count;

}

int main(){

int i , j;

root = new node;

for(i = 0 ; i < 26 ; i++){

root -> child[i] = 0;

root -> num = 0;

}

map<string , string>m;//创建一个map对象m

string str;

cin>>str;

while(cin>>str1){

if(str1 == "END")

break;

else{

cin>>str2;

m[str2] = str1;

Tree_Insert(str2);

}

}

cin>>str;

char s[3010];

int k;

getchar();

while(gets(s)){

if(strcmp(s , "END") == 0)

break;

int len = strlen(s);

s[len] = ' ';

string temp = "";

for(i = 0 ;i <= len ; i++){

if(s[i] < 'a' || s[i] > 'z'){

if(Tree_search(temp))

cout<<m[temp];

if(Tree_search(temp) == 0)

cout<<temp;

if(i != len)

cout<<s[i];

temp = "";

}

else

temp += s[i];

}

cout<<endl;

}

return 0;

}

代码2(直接map)

#include <iostream>

#include <cstdio>

#include <cstring>

#include <string>

#include <cstdlib>

#include <map>

using namespace std;

string str1 , str2;

int main(){

int i , j;

map<string , string>m;

string str;

cin>>str;

while(cin>>str1){

if(str1 == "END")

break;

else{

cin>>str2;

m[str2] = str1;

}

}

cin>>str;

char s[3010];

int k;

getchar();

while(gets(s)){

if(strcmp(s , "END") == 0)

break;

int len = strlen(s);

s[len] = ' ';

string temp ="";

for(i = 0 ;i <= len ; i++){

if(s[i] < 'a' || s[i] > 'z'){

if(m[temp] != "")

cout<<m[temp];

if(m[temp] == "")

cout<<temp;

if(i != len)

cout<<s[i];

temp = "";

}

else

temp += s[i];

}

cout<<endl;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: