1. 程式人生 > >Chinese Mahjong

Chinese Mahjong

bool ++ targe 思路 got tin while div const

OJ題號:UVa11210

思路:

首先字符串處理讀入手牌,str數組將手牌和數字對應,接下來搜索,先搜對子,如果搜過對子就不搜了。由於對子有且只有一個,可以在搜到以後直接跳出。同時註意一副麻將中每種牌只有4個,所以不能作為將。

 1 #include<cstdio>
 2 #include<string>
 3 #include<vector>
 4 #include<sstream>
 5 #include<iostream>
 6 using namespace std;
 7 vector<int> mahjong;
8 const string str[35]={"","1T","2T","3T","4T","5T","6T","7T","8T","9T","1S","2S","3S","4S","5S","6S","7S","8S","9S","1W","2W","3W","4W","5W","6W","7W","8W","9W","DONG","NAN","XI","BEI","ZHONG","FA","BAI"}; 9 void input(string line,vector<int> &ans) { 10 ans.clear(); 11 for(int i=0
;i<35;i++) ans.push_back(0); 12 stringstream ss(line); 13 string temp; 14 for(int i=0;i<13;i++) { 15 ss>>temp; 16 for(int j=1;j<=34;j++) { 17 if(temp==str[j]) { 18 ans[j]++; 19 break; 20 } 21 } 22
} 23 } 24 bool duizi=0,flag=0; 25 int ting; 26 bool hu() { 27 for(int i=1;i<=34;i++) { 28 if(mahjong[i]) { 29 goto Try; 30 } 31 } 32 cout<<" "+str[ting]; 33 flag=1; 34 return 1; 35 Try: 36 if(!duizi) { 37 for(int i=1;i<=34;i++) { 38 if(mahjong[i]>=2) { 39 mahjong[i]-=2; 40 duizi=1; 41 bool f=hu(); 42 duizi=0; 43 mahjong[i]+=2; 44 if(f) return 1; 45 } 46 } 47 return 0; 48 } 49 for(int i=1;i<=34;i++) { 50 if(mahjong[i]>=3) { 51 mahjong[i]-=3; 52 bool f=hu(); 53 mahjong[i]+=3; 54 if(f) return 1; 55 } 56 } 57 for(int i=1;i<=27;i++) { 58 if(i==8||i==9||i==17||i==18||i==26||i==27) continue; 59 if(mahjong[i]&&mahjong[i+1]&&mahjong[i+2]) { 60 mahjong[i]--; 61 mahjong[i+1]--; 62 mahjong[i+2]--; 63 bool f=hu(); 64 mahjong[i]++; 65 mahjong[i+1]++; 66 mahjong[i+2]++; 67 if(f) return 1; 68 } 69 } 70 return 0; 71 } 72 int main() { 73 int turn=0; 74 while(1) { 75 string s; 76 getline(cin,s); 77 if(s=="0") break; 78 turn++; 79 printf("Case %d:",turn); 80 mahjong.clear(); 81 input(s,mahjong); 82 flag=0; 83 for(ting=1;ting<=34;ting++) { 84 if(mahjong[ting]==4) continue; 85 mahjong[ting]++; 86 hu(); 87 mahjong[ting]--; 88 } 89 if(!flag) printf(" Not ready"); 90 printf("\n"); 91 } 92 return 0; 93 }

註:本隨筆整理自QQ空間舊文。發布時間為2017年1月22日。

查看原文

Chinese Mahjong