644 - Immediate Decodability(Update)

在 644 - Immediate Decodability 的解法中, 为了查找一个字符串是否在一个 vector 中, 使用了 <algorighm> 中的 search 函数, 感觉很不优美; 后来发出 find_if 函数可以满足我最初的想法, 使用 find_if 实现的代码如下:

有几个新知识点:
1. find_if 可以指定一个自定义 unary 函数进行比较.  
2. 使用 bind1st 把 binary 函数转为 unary 函数.
3. 使用 ptr_fun 把 function pointer 转化为 function object.

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <functional>  // bind1st
# include <cctype>
using namespace std;

// bind1st 或 bind2nd 在这里都是可用的,c++ 11 中 bind 更好用
// ptr_fun 转 function 指针为函数对象
// 若是简单的相等,可以直接用 equal_to<string>()

// 比较两个字符串相等, 当一个字符串是另一个字符串的前缀时也相等 
bool immediateCompare(string str1, string str2){
	int len = min(str1.size(), str2.size());

	for(int i=0; i<len; i++){
		if(str1[i] != str2[i])
			return false;
	}
	
	return true;
}


int main(int argc, char const *argv[])
{
	#ifndef ONLINE_JUDGE
		freopen ("644_i.txt", "r", stdin);  
		freopen ("644_o.txt", "w", stdout); 
	#endif
	
	int groupNum = 0;

	string line;
	bool immediately = true;
	vector<string> group;

	while(!cin.eof()){
		getline(cin, line);

		// 新的一个 group 开始, 输出并重置 immediately 和 group
		if(line == "9"){
			if(immediately){
				cout << "Set " << ++groupNum << " is immediately decodable" << endl;
			}else{
				cout << "Set " << ++groupNum << " is not immediately decodable" << endl;
			}

			immediately = true;
			group.clear();
			continue;
		}

		// 如果前面已经判断出是 not immediately 了, 那么后面的操作无需再进行
		if(!immediately)
			continue;

		// 判断 group 中是否有和当前 line 为前缀的字符串, 若有, 则 immediately 为 true 
		if(find_if(group.begin(), group.end(), bind1st(ptr_fun(immediateCompare), line)) != group.end())
			immediately = false;

		group.push_back(line);

	}


	return 0;
}

环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

你可能感兴趣的:(immediate,uva,644,Decodability)