生活随笔
收集整理的這篇文章主要介紹了
单词博弈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
甲乙兩個人用一個英語單詞玩游戲。兩個人輪流進行,每個人每次從中刪掉任意一個字母,如果剩余的字母序列是嚴格單調遞增的(按字典序a < b < c <....<z),則這個人勝利。兩個人都足夠聰明(即如果有贏的方案,都不會選輸的方案?),甲先開始,問他能贏么?
輸入: 一連串英文小寫字母,長度不超過15,保證最開始的狀態不是一個嚴格單增的序列。
輸出:1表示甲可以贏,0表示甲不能贏。
例如: 輸入 bad, 則甲可以刪掉b或者a,剩余的是ad或者bd,他就贏了,輸出1。
又如: 輸入 aaa, 則甲只能刪掉1個a,乙刪掉一個a,剩余1個a,乙獲勝,輸出0。?
?
解題思路:
1.對于給定的字符串root,甲先處理的結果只有兩種可能,必勝或者必敗
那么從root中取出一個?字符,一共有四種情況
oot???? rot??? rot??? roo,其中rot情況是重復的,編程的時候可以去掉重復的
2.對上面四個剩余字符串重復步驟1進行判斷,判斷其中是否有必敗字符串,如果有,那么root就肯定為必勝字符串。
public class Chuck{public static Dictionary<
string,
int> dictionaryStr =
new Dictionary<
string,
int>
();static void Main(
string[] args){string word =
"abcdcabghwhgaha";Console.WriteLine("輸入的字符串為{0}", word);Stopwatch time =
new Stopwatch();time.Start();who(word);//foreach (KeyValuePair<string, int> a in dictionaryStr)//{// Console.WriteLine("優先處理字符串{0}的人的結局為{1}", a.Key, a.Value);//}Console.WriteLine(
"游戲結果為{0}", dictionaryStr[word]);time.Stop();Console.WriteLine("運行時間為{0}ms", time.ElapsedMilliseconds);Console.ReadLine();}public static int who(
string word){bool flag;int count;
//計算必勝字符串的數量if (word.Length ==
2){if (dictionaryStr.ContainsKey(word) ==
false){dictionaryStr.Add(word, 1);
//只有兩個字符構成的字符串為"必勝字符串"
}}else{string str1 =
"";count =
0;for (
int i =
0; i < word.Length; i++
){str1 = word.Substring(
0, i) + word.Substring(i +
1, word.Length - i -
1);flag =
Judge(str1);if (flag ==
true)
//從word中刪除一個字符,剩下的字符串嚴格單增
{if (dictionaryStr.ContainsKey(word) ==
false){dictionaryStr.Add(word, 1);
//word為必勝字符串break;}}else{//從word中刪除一個字符,剩下的字符串不是嚴格單增if (dictionaryStr.ContainsKey(str1) ==
false)
//剩下的字符串不在字典里,無法獲取字符串是否為必勝字符串
{if (who(str1) ==
1)
//剩下的字符串為必勝字符串
{count++
;}else{//必敗字符串出現,說明word為必勝字符串break;
//如果想要得到所有可能的取字符串的方法,可以考慮不break
}}else //剩下的字符串存在于字典中,可以直接獲取字符串是否為必勝字符串
{if (dictionaryStr[str1] ==
1)
//必勝字符串
{count++
;}else{//必敗字符串出現,說明word為必勝字符串break;
//如果想要得到所有可能的取字符串的方法,可以考慮不break
}}}}//從word字符串[word長度為N]取出一個字符后,一共會有N種情況//字符串總數N-必勝字符串數=必敗字符串數if (word.Length - count >=
1)
//必敗字符串存在,則word為必勝字符串
{if (dictionaryStr.ContainsKey(word) ==
false){dictionaryStr.Add(word, 1);}}else//必敗字符串不存在,則word為必敗字符串
{if (dictionaryStr.ContainsKey(word) ==
false){dictionaryStr.Add(word, 0);}}}return dictionaryStr[word];}/// <summary>/// 判斷字符串是否是嚴格遞增的/// </summary>/// <param name="str"></param>/// <returns>返回true表示嚴格單增,返回false表示非嚴格單增</returns>public static bool Judge(
string str){bool flag =
true;
//假設字符串是嚴格單增的for (
int i =
0; i < str.Length -
1; i++
){if (str[i] < str[i +
1]){}else{flag =
false;break;}}return flag;}}
轉載于:https://www.cnblogs.com/chucklu/p/3491788.html
總結
以上是生活随笔為你收集整理的单词博弈的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。