单词博弈C++版本

#include <iostream>
#include <string>
#include <iterator>
#include <map>
using namespace std ;
//该程序参考了博主<a target=_blank href="http://blog.csdn.net/miss_ruochen/article/details/17201057">http://blog.csdn.net/miss_ruochen/article/details/17201057</a>
// judge if district ascend order
bool if_ascend_order(string str){
	for ( int i = 0 ; i < str.length()-1 ; ++ i){
		if( str[i+1] <= str[i] ){
			return false ;
		}
	}
	return true ;
}

string get_substr( string str, int loc){
	string temp = "" ;
	for ( int i = 0 ; i < str.length() ; ++ i){
		if( i != loc){
			temp += str[i] ;
		}
	}
	return temp ;
}

int WordGame( string word, map<string,int> &has){

	//if the length is 2, then A win the game
	if ( word.length() == 2 ){
		return 1 ;
	}

	//then in the iteration, check if the currunt word has been stored in the map
	map<string,int>::iterator it = has.find(word) ;
	if ( it != has.end() ){
		if( it->second == 0){
			return 0 ;
		}
		else{
			return 1 ;
		}
	}

	//if the length is 3
	if( word.length() == 3 ){
		if( word[0]>=word[1] && word[1] >= word[2]){
			has.insert(pair<string,int>(word,0));
			return 0 ;
		}
		else{
			has.insert(pair<string,int>(word,1));
			return 1;
		}
	}

	//according to the rule, check if delete one of the letter, A can win or not
	for(int i = 0 ; i < word.length() ; ++ i){
		if ( i != 0 && word[i]!=word[i-1]){
			continue ;
		}
		string temp = get_substr(word,i) ;
		if ( if_ascend_order(temp)){
			has.insert(pair<string,int>(word,1));
			return 1 ;
		}
	}

	//if A can't win in the first iteration, we need to check if B will lose
	for(int i = 0 ; i < word.length() ; ++ i){

		if( i != 0 && word[i] == word[i-1] ){
			continue ;
		}
		string temp = get_substr(word,i) ;

		map<string,int>::iterator jt = has.find(temp) ;
		// At this time, it seems like the B is doing the choice, if the state of the current 
		// word is a definite loser state, we can say that A will win.
		int state ;
		if( jt == has.end() ){
			state = WordGame(temp,has) ;
			has.insert(pair<string,int>(temp,state));
		}
		else{
			state = jt->second ;
		}

		if( state == 0 ){
			return 1 ;
		}
	}

	// if the WordGame(temp,has) == 1 means that B is in a definete winner state, so A will lose
	has.insert(pair<string,int>(word,0));
	return 0 ;
}

int main(){
	string str ;
	cin >> str ;
	map<string,int> test ;
	cout << WordGame(str,test) ;
	return 0 ;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值