1018 锤子剪刀布 (20 分)
大家应该都会玩“锤子剪刀布”的游戏:两人同时给出手势,胜负规则如图所示:
现给出两人的交锋记录,请统计双方的胜、平、负次数,并且给出双方分别出什么手势的胜算最大。
输入格式:
输入第 1 行给出正整数 N(≤105),即双方交锋的次数。随后 N 行,每行给出一次交锋的信息,即甲、乙双方同时给出的的手势。C
代表“锤子”、J
代表“剪刀”、B
代表“布”,第 1 个字母代表甲方,第 2 个代表乙方,中间有 1 个空格。
输出格式:
输出第 1、2 行分别给出甲、乙的胜、平、负次数,数字间以 1 个空格分隔。第 3 行给出两个字母,分别代表甲、乙获胜次数最多的手势,中间有 1 个空格。如果解不唯一,则输出按字母序最小的解。
输入样例:
10
C J
J B
C B
B B
B C
C C
C B
J B
B C
J J
输出样例:
5 3 2
2 3 5
B B
解题思路:
很直接的一个想法就是按甲乙给出的手势分类,计算甲乙赢的总次数和各种手势赢的次数。
可以用一个结构体来存放甲乙三种手势的获胜次数,排序后输出获胜次数最多的手势。 题中要求按字典序输出最小的解,所以结构体中的手势要初始化为BCJ,然后sort排序(从大到小)输出首个元素就行。
代码:
#include<iostream>
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
struct gest{
int cnt=0;
char c;
}gestA[3],gestB[3];
bool cmp(gest a, gest b){
return a.cnt>b.cnt;
}
int main(){
int n,cntA=0,cntB=0,cntEqu=0;// BCJ字典序
char a,b;
gestA[0].c='B'; gestA[1].c='C',gestA[2].c='J';
gestB[0].c='B'; gestB[1].c='C',gestB[2].c='J';
cin>>n;
for(int i=0; i<n; i++){
cin>>a>>b;
if(a=='J' && b=='C'){
cntB++;
gestB[1].cnt++;
}
else if(a=='J' && b=='B'){
cntA++;
gestA[2].cnt++;
}
else if(a=='B' && b=='J'){
cntB++;
gestB[2].cnt++;
}
else if(a=='B' && b=='C'){
cntA++;
gestA[0].cnt++;
}
else if(a=='C' && b=='J') {
cntA++;
gestA[1].cnt++;
}
else if(a=='C' && b=='B'){
cntB++;
gestB[0].cnt++;
}
else{
cntEqu++;
}
}
sort(gestA, gestA+3, cmp);
sort(gestB, gestB+3, cmp);
printf("%d %d %d\n", cntA, cntEqu, cntB);
printf("%d %d %d\n", cntB, cntEqu, cntA);
printf("%c %c", gestA[0].c, gestB[0].c);
return 0;
}
第二种方式:
注意到BCJ恰好是相克的顺序,可以将BCJ对应一维数组的0、1、2位。读入手势之后转换为数字a、b,甲胜利的条件就是
(a+1)%3 = b。
代码:
#include<iostream>
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
int change(char c){
if(c=='B') return 0;
if(c=='C') return 1;
return 2;
}
int main(){
int n,cntA=0,cntB=0,cntEqu=0,a,b,gestA[3]={0},gestB[3]={0};// BCJ字典序
char c1,c2;
cin>>n;
for(int i=0; i<n; i++){
cin>>c1>>c2;
a = change(c1);
b = change(c2);
if((a+1)%3 == b){
cntA++;
gestA[a]++; //获胜的手势+1
}else if(a == b)
cntEqu++;
else{
cntB++;
gestB[b]++;
}
}
int Amax=0, Bmax=0;
for(int i=0; i<3; i++) if(Amax < gestA[i]) Amax = gestA[i];
for(int i=0; i<3; i++) if(Bmax < gestB[i]) Bmax = gestB[i];
if(Amax == gestA[0]) c1 = 'B';
else if(Amax == gestA[1]) c1='C';
else c1 = 'J';
if(Bmax == gestB[0]) c2 = 'B';
else if(Bmax == gestB[1]) c2='C';
else c2 = 'J';
printf("%d %d %d\n", cntA, cntEqu, cntB);
printf("%d %d %d\n", cntB, cntEqu, cntA);
printf("%c %c", c1, c2);
return 0;
}