利用固定克制表把石头/剪子/布的胜负判断转换为 O(1) 查询,再逐局输出结果。
OJ: roj
题目 ID: 1132
难度:入门
标签:模拟字符串映射
创建: 2026-09-29 20:25
更新: 2026-10-05 02:58
题目描述
石头剪子布规则:石头打剪刀,剪刀剪布,布包石头。共 S1 S2,两人出法均取自 {"Rock", "Scissors", "Paper"}(大小写敏感)。对每局输出一行胜者 Player1 或 Player2,平局输出 Tie。
样例输入:
text
3
Rock Scissors
Paper Paper
Rock Paper样例输出:
text
Player1
Tie
Player2思路
每局直接查固定的克制关系表:Rock 克 Scissors,Scissors 克 Paper,Paper 克 Rock。用映射 win_over[s] 表示被 s 克制的出法:出法相同输出 Tie,否则 win_over[S1] == S2 时 Player1 胜,反之 Player2 胜。整体
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 20:30
# update_at: 2026-09-29 20:30
import sys
# 石头/剪子/布 的克制关系:key 能赢 value。
WIN_OVER = {"Rock": "Scissors", "Scissors": "Paper", "Paper": "Rock"}
def judge(a: str, b: str) -> str:
"""判断一局猜拳的胜者。"""
if a == b:
return "Tie"
if WIN_OVER[a] == b:
return "Player1"
return "Player2"
def solve() -> None:
data = iter(sys.stdin.buffer.read().split())
n = int(next(data))
out = [judge(next(data).decode(), next(data).decode()) for _ in range(n)]
print("\n".join(out))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 02:58
* update_at: 2026-10-05 02:58
*/
#include <iostream>
#include <string>
#include <map>
typedef long long ll;
ll n; // 游戏局数
std::map<std::string, std::string> win_over; // win_over[s] = 被 s 克制的出法
int main() {
// 固定克制表:石头克剪刀,剪刀克布,布克石头
win_over["Rock"] = "Scissors";
win_over["Scissors"] = "Paper";
win_over["Paper"] = "Rock";
std::cin >> n;
for (ll i = 1; i <= n; ++i) {
std::string s1, s2;
std::cin >> s1 >> s2;
if (s1 == s2)
std::cout << "Tie\n";
else if (win_over[s1] == s2)
std::cout << "Player1\n";
else
std::cout << "Player2\n";
}
return 0;
}