现在的位置: 首页 > 综合 > 正文

PKU 2503–tire买一送一

2014年02月28日 ⁄ 综合 ⁄ 共 997字 ⁄ 字号 评论关闭

PS:代码

#include<iostream>
#include<string>
#define maxn 2000000
using namespace std;
struct TREE
{
	bool flag;
	int nxt[26];
	char words[15];
};
TREE tree[maxn];
int loc;
void init()
{
	loc = 2;
	tree[1].flag = 0;
	for(int i=0;i<26;i++)
		tree[1].nxt[i] = -1;
}
void insert(char chfront[],char chrear[])
{
	int p = 1,pos,len = strlen(chrear);
	for(int i=0;i<len;i++)
	{
		pos = chrear[i]-'a';
		if(tree[p].nxt[pos] != -1)
			p = tree[p].nxt[pos];
		else
		{
			tree[p].nxt[pos] = loc;
			tree[loc].flag = 0;
			for(int i=0;i<26;i++)
				tree[loc].nxt[i]=-1;
			p=loc;	
			loc++;
		}
		if(i == len-1)
		{
			tree[p].flag = 1;
			strcpy(tree[p].words,chfront);
		}
	}
}
void search(char chfront[],char chrear[])
{
	int p = 1,len = strlen(chrear),pos,i;
	for(i=0;i<len;i++)
	{
		pos = chrear[i]-'a';
		if(tree[p].nxt[pos] == -1)
            break;
		p = tree[p].nxt[pos];
	}
	if(i==len && tree[p].flag == 1)
		strcpy(chfront,tree[p].words);
}
int main()
{
	char chfront[30],chrear[30],ch[60];
	init();
	while(gets(ch)!=NULL && ch[0])
	{
		sscanf(ch,"%s %s",chfront,chrear);
		insert(chfront,chrear);
	}
	while(scanf("%s",chrear)!=EOF && chrear[0])
	{
		strcpy(chfront,"eh");
		search(chfront,chrear);
		printf("%s\n",chfront);
	}	
	return 0;
}

 

抱歉!评论已关闭.