题目链接

斗兽棋

题目描述

牛牛和牛妹在玩一个博弈游戏。每人从 elephant, tiger, cat, mouse 四种棋子中选择一个。 胜负规则形成一个循环克制链:

  • elephanttiger
  • tigercat
  • catmouse
  • mouseelephant

如果一方的棋子能吃掉另一方,则该方获胜;否则为平局(即双方出一样的棋子)。

输入描述:

  • 在一行输入两个以空格分隔的字符串 s1s2,分别代表牛牛和牛妹所出的棋子。

输出描述:

  • 如果牛牛获胜,输出 win
  • 如果牛妹获胜(即牛牛失败),输出 lose
  • 如果平局,输出 tie

示例:

  • 输入: tiger elephant
  • 输出: lose
  • 说明: 牛牛出 tiger,牛妹出 elephant。大象吃老虎,所以牛牛输了。

解题思路

这道题的本质是实现一个固定的、小规模的规则集。根据您的建议,我们可以通过将核心逻辑抽象成一个函数来让代码结构更清晰、更优雅。

  1. 读取输入: 首先,程序需要读取代表牛牛和牛妹选择的两个字符串。

  2. 抽象规则为函数: 我们可以创建一个函数,例如 can_eat(attacker, defender)。这个函数专门负责判断"吃"这个行为:

    • 它接受两个字符串参数:攻击方和防守方。
    • 函数内部包含所有的克制规则。如果 attacker 能吃掉 defender,则返回 true,否则返回 false
  3. 判断逻辑 (优化版): 有了辅助函数后,我们可以构建一个非常清晰且完全符合规则的判断链:

    • 第一步:判断牛牛获胜 (Win) 调用 can_eat(niuniu, niumei)。如果返回 true,说明牛牛获胜。

    • 第二步:判断牛妹获胜 (Lose) 如果牛牛没赢,接着调用 can_eat(niumei, niuniu)。如果返回 true,说明牛妹获胜,牛牛失败。

    • 第三步:处理平局 (Tie) 如果以上两种情况都未发生,即牛牛不能吃掉牛妹,并且牛妹也不能吃掉牛牛,那么根据规则"否则为平局",最终结果就是平局。这种情况包含了双方出子相同以及双方出子不同但无法相互克制(如 elephant vs cat)的所有场景。

这种方法将"规则是什么"(can_eat 函数)和"如何根据规则定胜负"(主函数逻辑)清晰地分离开来,并且逻辑严谨,是最佳的程序设计。

代码

#include <iostream>
#include <string>

using namespace std;

// 函数:判断 s1 是否能吃掉 s2
bool can_eat(const string& s1, const string& s2) {
    return (s1 == "elephant" && s2 == "tiger") ||
           (s1 == "tiger" && s2 == "cat") ||
           (s1 == "cat" && s2 == "mouse") ||
           (s1 == "mouse" && s2 == "elephant");
}

int main() {
    string niuniu, niumei;
    cin >> niuniu >> niumei;
    
    if (can_eat(niuniu, niumei)) {
        cout << "win" << endl;
    } else if (can_eat(niumei, niuniu)) {
        cout << "lose" << endl;
    } else {
        cout << "tie" << endl;
    }
    
    return 0;
}
import java.util.Scanner;

public class Main {
    // 方法:判断 s1 是否能吃掉 s2
    private static boolean canEat(String s1, String s2) {
        return (s1.equals("elephant") && s2.equals("tiger")) ||
               (s1.equals("tiger") && s2.equals("cat")) ||
               (s1.equals("cat") && s2.equals("mouse")) ||
               (s1.equals("mouse") && s2.equals("elephant"));
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String niuniu = sc.next();
        String niumei = sc.next();
        
        if (canEat(niuniu, niumei)) {
            System.out.println("win");
        } else if (canEat(niumei, niuniu)) {
            System.out.println("lose");
        } else {
            System.out.println("tie");
        }
    }
}
def can_eat(s1, s2):
    """判断 s1 是否能吃掉 s2"""
    return (s1 == "elephant" and s2 == "tiger") or \
           (s1 == "tiger" and s2 == "cat") or \
           (s1 == "cat" and s2 == "mouse") or \
           (s1 == "mouse" and s2 == "elephant")

niuniu, niumei = input().split()

if can_eat(niuniu, niumei):
    print("win")
elif can_eat(niumei, niuniu):
    print("lose")
else:
    print("tie")

算法及复杂度

  • 算法: 条件逻辑判断。
  • 时间复杂度: 。程序的执行路径只涉及少数几次字符串比较。由于字符串的可能值和长度都是固定的,所以比较操作的时间可以视为常数。
  • 空间复杂度: 。仅需要常数级别的空间来存储两个输入的字符串。