uva 508

博客讨论了UVA 508题目,指出原题描述的错误——在匹配多个单词时应选择字典序最小的一个。文章通过比较不同的解题方法,如使用map和模拟法,强调了正确理解问题和选择合适算法的重要性。作者提到一开始的模拟法导致超时,但后来发现只需检查context中的子串并计算长度差即可,这一转变显著提高了效率。

原题

莫尔斯电码匹配

紫书上的描述是错的...遇到可匹配 的多个单词 , 应该选择字典序最小的那个而不是任意一个输出, 

所以用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;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值