使用胜负映射判断每轮石头剪刀布,并输出 Player1、Player2 或 Tie。
OJ: noi_openjudge
题目 ID: ch0107-04
难度:入门
标签:字符串模拟python
日期: 2026-07-30 23:01
题意
对每轮石头剪刀布输出胜者或平局。
思路
字典记录每种出拳战胜的对象。先判断相同出拳,再判断 Player1 的映射结果是否等于 Player2,剩余情况就是 Player2 胜。
代码
Python代码
python
round_count = int(input())
wins_against = {"Rock": "Scissors", "Scissors": "Paper", "Paper": "Rock"}
for _ in range(round_count):
first, second = input().split()
if first == second:
print("Tie")
elif wins_against[first] == second:
print("Player1")
else:
print("Player2")C++代码
cpp
#include <cstdio>
#include <cstring>
char val[][20] = { "Scissors", "Paper", "Rock" };
int n;
char str1[20];
char str2[20];
int main(){
scanf("%d",&n);
int i,j;
for (i=1;i<=n;i++){
scanf("%s",str1);
scanf("%s",str2);
int idx_1,idx_2;
for (j=0;j<3;j++){
if( strcmp(str1,val[j]) == 0)
idx_1 = j;
if( strcmp(str2,val[j]) == 0)
idx_2 = j;
}
if( idx_1 == idx_2)
printf("Tie\n");
//else if ( (idx_1 == 0 && idx_2 == 1) || (idx_1 == 1 && idx_2 == 2) || (idx_1 == 2 && idx_2 == 0))
else if( (idx_1+1) % 3 == idx_2 )
printf("Player1\n");
else
printf("Player2\n");
}
return 0;
}复杂度
时间复杂度为
总结
用映射表描述固定胜负规则,可避免冗长的条件组合。