What Are You Talking About
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 102400/204800 K (Java/Others)
Total Submission(s): 5064 Accepted Submission(s): 1522
題目大意:給你一些字符串和對應的字符串,然後給出一些話,然後根據之前的字符串來對應輸出,如果沒有對應,則輸出原來的字符串。
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <string>
using namespace std;
struct node
{
bool flag; //標記-判斷是否有字符串
char ch[25]; //該結點的字符串
node *next[26]; //鏈表結點
};
node *root, memory[1000005];
int cnt = 0;
node* create_node()
{
node *p = &memory[cnt++];
p->ch[0] = 0;
p->flag = false;
for(int i = 0; i < 26; i++)
{
p->next[i] = NULL;
}
return p;
}
void insert_node(char *s, char *res)
{
node *p = root;
int i, k;
for(i = 0; s[i]; i++)
{
k = s[i] - 'a';
if(p->next[k] == NULL)
{
p->next[k] = create_node();
}
p = p->next[k];
}
strcpy(p->ch, res);
p->flag = true;
}
char* search_node(char *s)
{
node *p = root;
int i, k;
for(i = 0; s[i]; i++)
{
k = s[i] - 'a';
if(p->next[k] == NULL) return s;
else p = p->next[k];
}
if(p->flag == true) return p->ch; //注意!要標記爲true才返回p->ch
else return s;
}
int main()
{
int i, num, len;
char ch[25], sh[25], hh[3005];
scanf("%s", ch);
root = create_node();
while(scanf("%s", ch))
{
if(strcmp(ch, "END") == 0) break;
scanf("%s", sh);
insert_node(sh, ch);
}
scanf("%s", ch);
getchar();
while(1)
{
gets(hh);
if(strcmp(hh, "END") == 0) break;
len = strlen(hh);
hh[len] = ' '; //末尾加多一個空格' ',更好判斷
hh[++len] = 0; //結束符爲0 或者 '\0'
num = 0;
for(i = 0; i < len; i++)
{
if(hh[i] >= 'a' && hh[i] <= 'z')
{
sh[num++] = hh[i];
}
else
{
sh[num] = 0;
num = 0;
cout << search_node(sh);
if(i != len - 1) cout << hh[i];
}
}
cout << endl;
}
return 0;
}