莫尔斯电码匹配
紫书上的描述是错的...遇到可匹配 的多个单词 , 应该选择字典序最小的那个而不是任意一个输出,
所以用map真的好看很多
还有一开始看到在尾部增删code, 直接采用模拟法了, 导致一开始TLE了两次, 还以为是map效率太低了...
其实只要从context中一一取出来找包含的字串, 然后有包含的计算长度差即可...
有时候换一个角度想问题, 效率不止高了一点点
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
#include <list>
using namespace std;
const int MAXN = 60;
const int SIZE = 6;
const int BASE = 1000000;
typedef long long LL;
/*
uva 508
关键 : 1. 字符串字串包含问题
2. map容器的使用
*/
map<char,string> table;
map<string,string> words;
template <typename T>
void test(T begin,T end){
T it = begin;
while( it!=end ){
cout << it->first << " : " << it->second << endl;
it++;
}
}
int match(const string code,string & ans){
int cnt = 0;
ans.clear();
for(map<string,string>::iterator it=words.begin(); it!=words.end(); it++){
if( code==it->second ){
if( ans.length()==0 ){
ans = it->first;
}
cnt++;
}
}
return cnt;
}
int substring(string str1,string str2){
// 检测两个字符串之间是否有包含关系, 有则返回长度差, 无则返回一个大整数
if( str1.length()>str2.length() ){
string s = str1;
str1 = str2;
str2 = s;
}
if( str1==str2.substr(0,str1.length()) ){
return ( str2.length()-str1.length() );
}
return BASE;
}
string solve(string code){
// flag = 0(正常匹配), 1(多个单词匹配), 2(模糊匹配)
string ans;
int result = 0, flag = 0, tmp = 0;
result = match(code,ans);
// cout << "result=" << result << endl;
if( result==1 ){
flag = 0;
}else if( result > 1 ){
flag = 1;
}else {
flag = 2;
result = BASE;
for(map<string,string>::iterator it=words.begin(); it!=words.end(); it++){
tmp = substring(code,it->second);
if( tmp<result ){
result = tmp;
ans = it->first;
}
}
if( result==BASE ){
ans = words.begin()->first;
}
}
if( flag ){
ans += ( flag==1? "!":"?" );
}
return ans;
}
int main(){
// freopen("input.txt","r",stdin);
char ch;
string str,str2;
while( (cin>>ch)&&ch!='*' ){
cin >> str;
table.insert(pair<char,string>(ch,str));
}
while( (cin>>str)&&str!="*" ){
str2.clear();
for(int i=0; i<str.length(); i++){
str2 += table[str[i]];
}
words.insert(pair<string,string>(str,str2));
}
while( (cin>>str)&&str!="*" ){
cout << solve(str) << endl;
}
return 0;
}
博客讨论了UVA 508题目,指出原题描述的错误——在匹配多个单词时应选择字典序最小的一个。文章通过比较不同的解题方法,如使用map和模拟法,强调了正确理解问题和选择合适算法的重要性。作者提到一开始的模拟法导致超时,但后来发现只需检查context中的子串并计算长度差即可,这一转变显著提高了效率。
318

被折叠的 条评论
为什么被折叠?



