您的位置:首页 > 其它

PAT (Basic Level)1018. 锤子剪刀布

2016-02-24 16:18 453 查看
http://www.patest.cn/contests/pat-b-practise/1018

题目描述:

大家应该都会玩“锤子剪刀布”的游戏:两人同时给出手势,胜负规则如图所示:



现给出两人的交锋记录,请统计双方的胜、平、负次数,并且给出双方分别出什么手势的胜算最大。

输入格式:

输入第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


这题只需要两个二维统计数组就可以了,一组统计甲乙胜平负的次数,一组统计胜时甲乙用B、C和F的次数。在这里有个小技巧,不需要把每种情况罗列得到胜负情况。只需要将两字符作差,得到的差为-1、-7或者8时,前者胜;差为0,平;或者后者胜。

#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <ctype.h>
using namespace std;

int main()
{
int N = 0;
char jia=' ', yi=' ';
int win[2][3]={0}; //win flat lose
int count[2][3]={0};//count B C J when win

cin >> N;
while(N--)
{
cin >> jia >> yi ;
int temp = jia-yi;
if (temp==0) {
win[0][1]++;
win[1][1]++;
}
else if (temp == -1 ||temp==-7 || temp==8)
{
win[0][0]++;
win[1][2]++;
if (jia=='B') count[0][0]++;
else if (jia=='C') count[0][1]++;
else count[0][2]++;
}
else
{
win[1][0]++;
win[0][2]++;
if (yi=='B') count[1][0]++;
else if (yi=='C') count[1][1]++;
else count[1][2]++;
}
}

int maxtemp=-1;
char shoushi[3]={'B', 'C', 'J'};
for (int i =0 ; i<3 ; i++)
{
if(count[0][i] >maxtemp){
maxtemp = count[0][i];
jia= shoushi[i];
}
}
maxtemp=-1;
for (int i =0 ; i<3 ; i++)
{
if(count[1][i] > maxtemp){
maxtemp = count[1][i];
yi= shoushi[i];
}
}

cout << win[0][0] <<' ' << win[0][1] <<' ' <<win[0][2] << endl;
cout << win[1][0] <<' ' << win[1][1] <<' ' <<win[1][2] << endl;
cout << jia <<' ' << yi << endl;

return 0;
}


再附上俺家小胖子写的更巧妙的代码:

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

int main() {
char A, B;
string res;
int N;
int numW=0, numT=0, numF=0;
int count1[26] = { 0 };
int count2[26] = { 0 };
cin >> N;
while (N--) {
cin >> A >> B;
if (A == B)
numT++;
else {
res = "";
res = res + A + B;
if (res == "CJ" || res == "JB" || res == "BC"){
numW++;
count1[res[0] - 'A']++;
}
else {
numF++;
count2[res[1] - 'A']++;
}
}
}
int maxA = -1, maxB = -1;
char resA, resB;
for (int i = 1; i < 26; i++) {
if (maxA < count1[i])
{
maxA = count1[i];
resA = 'A' + i;
}
if (maxB < count2[i]) {
maxB = count2[i];
resB = 'A' + i;
}
}
cout << numW << " " << numT << " " << numF << endl;
cout << numF << " " << numT << " " << numW << endl;
cout << resA << " " << resB << endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: