# Greedy# String# Array

d217 - 00489 - Hangman Judge

🔗 前往 ZeroJudge 原題

題目描述

本題模擬 Hangman 遊戲,給定答案單字和玩家的猜測,判斷玩家是贏、輸還是放棄。玩家猜測字母,若猜中則翻開答案中的對應字母,猜錯則在 Hangman 圖上加一劃。

解題思路

程式使用兩個布林陣列 aabb 分別記錄答案單字中每個字母是否已被猜中,以及玩家是否猜過該字母。迴圈遍歷玩家的猜測,如果猜中的字母數量等於答案單字中不同字母的數量,則玩家獲勝。如果猜錯的次數達到 7 次,則玩家失敗。如果玩家在未獲勝或失敗前停止猜測,則玩家放棄。

複雜度分析

  • 時間複雜度: O(N*M),其中 N 是測試案例數量,M 是單字長度。
  • 空間複雜度: O(1),因為 aabb 陣列的大小固定為 26。

程式碼

#include <bits/stdc++.h>
using namespace std;
int n;
string a,b;
bool aa[26],bb[26];
int main(){
	cin.tie(0); ios::sync_with_stdio(0);
	while(cin >> n){
		if(n==-1)break;
		memset(aa,0,sizeof(aa));
		memset(bb,0,sizeof(bb));
		cin >> a >> b;
		int ct=0,ans=0,wa=0;
		bool ls=0,wi=0;
		for(int i=0;i<a.size();++i){
			if(!aa[a[i]-'a'])++ans;
			aa[a[i]-'a']=1;
		}
		for(int i=0;i<b.size();++i){
			if(bb[b[i]-'a'])continue;
			bb[b[i]-'a']=1;
			if(aa[b[i]-'a']){
				++ct;
				if(ct==ans&&ls==0)wi=1;
			}
			else{
				++wa;
				if(wa>=7&&wi==0)ls=1;
			}
		}
		cout << "Round " << n << "\n";
		if(ls){
			cout << "You lose.\n";
		}
		else if(wi){
			cout << "You win.\n";
		}
		else{
			cout << "You chickened out.\n";
		}
	}
}

Discussion