Hangman Judge UVA - 489

https://vjudge.net/problem/UVA-489

也是用来练自顶向下编程,练习用函数来解题的,还是先定好思路,写大体框架,再扩展每个函数的功能。

不难,具体代码里有注解。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

void Print(int flag, int n)//win 1,lose 0, chickened out -1
{
    cout << "Round " << n << endl;
    if (flag == 0)cout << "You lose.";
    else if (flag == 1)cout << "You win.";
    else cout << "You chickened out.";
    cout << endl;
}

int judge(string &S1,string &S2)
{
    sort(S1.begin(), S1.end());
    S1.erase(unique(S1.begin(), S1.end()), S1.end());
    int book[100]; memset(book, 0, sizeof(book));
    string::iterator it = S1.begin();
    for (; it != S1.end(); it++) book[*it-65]++;
    
    int cnt1 = 0;//猜错次数计数器。
    int cnt2 = 0;//猜对计数器
    it = S2.begin();
    //猜数字
    while (it != S2.end()&&cnt2!=S1.size())//要判断是否已经全部猜对,防止win后不断猜最终判定为lose的结果。
    {
        if (book[*it-65] != 1) cnt1++;
        else cnt2++; 
        book[*it-65]--; it++;
    }
    
    bool win = true;//是否赢了?
    for (int i = 0; i < 100; i++)
        if (book[i] > 0) win = false;

    if (cnt1 > 6) return 0;//cnt>6的情况,输了
    else if (win) return 1;//win==true的情况,赢了
    else return -1;//否则,没有错完也没有赢,放弃。
}
int main()
{
    int n;
    while (cin >> n)
    {
        if (n == -1) break;
        //输入部分
        string S1, S2;
        cin >> S1 >> S2;
        //判断
        int flag=judge(S1,S2);
        //输出
        Print(flag, n);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/worldcreator-zh/p/10584644.html