您的位置:首页 > 理论基础 > 数据结构算法

我的poj第一道数据结构--poj1035

2014-05-28 01:19 253 查看
这道题可以说很简单的吧,好像没有体现什么数据结构,就是查了好久的c++的工具书,去学习<string>类的函数,到头来也只是用了.length=.=!

其实,刚开始也没有想出来这道题怎么做的....

先看一下题的最关键的地方

deleting of one letter from the word; 
replacing of one letter in the word with an arbitrary letter; 
inserting of one arbitrary letter into the word. 
Your task is to write the program that will find all possible replacements from the dictionary for every given word. 

记住一点,就算是删除,替换,插入,他有一点没有改变,前缀!,所以说,例如是删除后相等的,当遇到前缀不相等的情况就可以,掠过一位,再次比较,如果发现还不相等,那就真不相等了,其他的方式和这个原理类似

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
string dic[10010];
string word[55];
bool change (string word,string dic)
{
int count=0;
for(int i=0;i<word.length();i++)
{
if(word[i]!=dic[i])
{
count++;
if(count>1)
return false;
}
}
return true;
}
bool del(string word,string dic)
{
int dif=0;
int sword=0;
int sdic=0;
for(int i=0;i<word.length();i++)
{
if(word[sword]!=dic[sdic])
{
dif++;
sword++;
if(dif>1)
return false;
}
else
{
sword++;
sdic++;
}
}
return true;
}
bool add(string word,string dic)
{
int dif=0;
int sword=0;
int sdic=0;
for(int i=0;i<dic.length();i++)
{
if(word[sword]!=dic[sdic])
{
dif++;
sdic++;
if(dif>1)
return false;
}
else
{
sword++;
sdic++;
}
}
return true;
}
int main()
{
std::ios::sync_with_stdio(false);
memset(dic,0,sizeof(dic));
memset(word,0,sizeof(word));
string s;
int k_word=0;
int k_dic=0;
while(cin>>s && s!="#")
{
dic[k_dic++]=s;
}
while(cin>>s && s!="#")
{
word[k_word++]=s;
}
int aa[10009];
int p=0;
for(int i=0;i<k_word;i++)
{
p=0;
memset(aa,0,sizeof(aa));
bool flag=false;
int len=word[i].length();
for(int j=0;j<k_dic;j++)
{
if(len==dic[j].length())
{
if(word[i]==dic[j])
{
flag=true;
break;
}
else if(change(word[i],dic[j]))
{
aa[p++]=j;
}
}
else if(len==dic[j].length()-1)
{
if(add(word[i],dic[j]))
{
aa[p++]=j;
}
}
else if(len==dic[j].length()+1)
{
if(del(word[i],dic[j]))
{
aa[p++]=j;
}
}
}
if(flag)
cout<<word[i]<<" is correct"<<endl;
else
{
cout<<word[i]<<": ";
for(int k=0;k<p;k++)
cout<<dic[aa[k]]<<' ';
cout<<endl;
}
}
return 0;
}


至于为什么要加上
std::ios::sync_with_stdio(false);这是有原因的,因为这句话可以提高cin的读取速度,但是,代价就是cin和scanf不能同时混用了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: