首页 > 试题广场 >

扑克牌大小

[编程题]扑克牌大小
  • 热度指数:49880 时间限制:C/C++ 10秒,其他语言20秒 空间限制:C/C++ 128M,其他语言256M
  • 算法知识视频讲解
扑克牌游戏大家应该都比较熟悉了,一副牌由54张组成,含3~A,2各4张,小王1张,大王1张。牌面从小到大用如下字符和字符串表示(其中,小写joker表示小王,大写JOKER表示大王):)
3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER
输入两手牌,两手牌之间用“-”连接,每手牌的每张牌以空格分隔,“-”两边没有空格,如:4 4 4 4-joker JOKER
请比较两手牌大小,输出较大的牌,如果不存在比较关系则输出ERROR

基本规则:
(1)输入每手牌可能是个子,对子,顺子(连续5张),三个,炸弹(四个)和对王中的一种,不存在其他情况,由输入保证两手牌都是合法的,顺子已经从小到大排列;
(2)除了炸弹和对王可以和所有牌比较之外,其他类型的牌只能跟相同类型的存在比较关系(如,对子跟对子比较,三个跟三个比较),不考虑拆牌情况(如:将对子拆分成个子)
(3)大小规则跟大家平时了解的常见规则相同,个子,对子,三个比较牌面大小;顺子比较最小牌大小;炸弹大于前面所有的牌,炸弹之间比较牌面大小;对王是最大的牌;
(4)输入的两手牌不会出现相等的情况。

答案提示:
(1)除了炸弹和对王之外,其他必须同类型比较。
(2)输入已经保证合法性,不用检查输入是否是合法的牌。
(3)输入的顺子已经经过从小到大排序,因此不用再排序了.

数据范围:保证输入合法

输入描述:
输入两手牌,两手牌之间用“-”连接,每手牌的每张牌以空格分隔,“-”两边没有空格,如4 4 4 4-joker JOKER。


输出描述:
输出两手牌中较大的那手,不含连接符,扑克牌顺序不变,仍以空格隔开;如果不存在比较关系则输出ERROR。
示例1

输入

4 4 4 4-joker JOKER

输出

joker JOKER
#include<iostream> #include<vector> #include<string.h> using namespace std; char firstCards[15],secCards[15]; int oneChar(char token) { switch (token) { case 'J': return 11; case 'Q': return 12; case 'K': return 13; case 'A': return 14; case '2': return 15; default: return atoi(&token); } } int Card(int *cardnum,char *cardStr) { int numcount=0; int charsize; for(char *token=strtok(cardStr," ");token!=nullptr;token=strtok(nullptr," ")) { charsize=strlen(token); if (charsize==1) { cardnum[numcount]=oneChar(*token); }else if (charsize==2) { cardnum[numcount]=10; }else if (charsize==5) { if(strcmp(token,"JOKER")) { cardnum[numcount]=100; }else { cardnum[numcount]=200; } } ++numcount; } return numcount; } void sameType(int firstCardNum,int secCardNum,int type) { if (firstCardNum>=secCardNum) { cout<<firstCards<<endl; }else { cout<<secCards<<endl; } } void diffType(int firstCardNum,int secCardNum,int firstType,int secType) { if(firstCardNum==100) cout<<firstCards<<endl; else if (secCardNum==100) cout<<secCards<<endl; else if(firstType==4) cout<<firstCards<<endl; else if(secType==4) cout<<secCards<<endl; else cout<<"ERROR"<<endl; } int main() { char twoCard[100]={0}; while (cin.getline(twoCard,sizeof(twoCard))) { char *firstCardstr=strtok(twoCard,"-"); char *secCardstr=strtok(nullptr,"-"); strcpy(firstCards,firstCardstr); strcpy(secCards,secCardstr); int firstCardNum[5]={0},secCardNum[5]={0}; int firstCardtype=0,secCardtype=0; firstCardtype=Card(firstCardNum,firstCardstr); secCardtype=Card(secCardNum,secCardstr); if(firstCardtype==secCardtype) { sameType(*firstCardNum,*secCardNum,firstCardtype); }else { diffType(*firstCardNum,*secCardNum,firstCardtype,secCardtype); } memset(firstCards,0,sizeof(firstCards)); memset(secCards,0,sizeof(secCards)); } return 0; }
编辑于 2016-07-08 22:10:13 回复(0)
//JAVA解法,选用HASH比较大小,复杂
//参考评论大神,若是用索引比较,肯定更简单。
import java.util.HashMap;
import java.util.Scanner;

/*length
 * 个子-1
 *'10'-2 
 * 对子-3 
 * 三个-5
 * **-7
 * 顺子-9
 * 对王-11
 */
/*
 * 1.忘记对‘10’这个特殊的牌进行处理
 * 2.思路可以改成,见到王炸旧输出王炸
 * 3.比较大小用索引更简单!!!!,用hashmap很复杂。
 */
public class Main {
	
	public static boolean boom(int length) {
		boolean boom = false;
		if(length == 7 || length == 11) boom = true;
		return boom;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<Character, Integer> hash = new HashMap<Character,Integer>() {
			{
				put('3',0);
				put('4',1);
				put('5',2);
				put('6',3);
				put('7',4);
				put('8',5);
				put('9',6);
				put('1',8);
				put('J',9);
				put('Q',10);
				put('K',11);
				put('A',12);
				put('2',13);
				put('j',14);
				put('J',15);
			}
		};
		Scanner sc = new Scanner(System.in);
		String before = sc.nextLine();
		String[] after = before.split("-");
//		for (String string : after) {
//			System.out.println(string);
//		}
		//System.out.println(after[1].length());
		
		int len_one = after[0].length();
		//System.out.println("len_one: " + len_one);
		int len_two = after[1].length();
		//System.out.println("len_two: " + len_two);
		if(len_one + len_two == 3) {
			if(len_one == 2) len_one = 1;
			else len_two = 1;
		}
		if(len_one + len_two == 8) {
			if(len_one == 5) len_one = 3;
			else len_two = 3;
		}
		if(len_one + len_two == 19) {
			if(len_one == 10) len_one = 9;
			else len_two = 9;
		}
		if (len_one == len_two) {
			char[] c_one = after[0].toCharArray();
			char[] c_two = after[1].toCharArray();
			int one = hash.get(c_one[0]);
			//System.out.println("one: " + one);
			int two = hash.get(c_two[0]);
			//System.out.println("two: " + two);
			if(one == two) {
				System.out.println("ERROR");
				return;
			}
			String ss = one>two?after[0]:after[1];
			System.out.println(ss);
			return;
		}else {
			if((len_one + len_two) == 18) {
				String ss = len_one==11? after[0]:after[1];
				System.out.println(ss);
				return;
			}
			if((len_one + len_two) == 22) {
				System.out.println("joker JOKER");
				return;
			}
			if (boom(len_one) || boom(len_two)) {
				String ss = boom(len_one)?after[0]:after[1];
				System.out.println(ss);
				return;
			}
			else {
				System.out.println("ERROR");
				return;
			}
		}
		
	}

}

发表于 2021-08-19 18:39:00 回复(0)
#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
map<string,int> comp {{"3",1},{"4",2},{"5",3},{"6",4},{"7",5},
                      {"8",6},{"9",7},{"10",8},{"J",9},{"Q",10},
                      {"K",11},{"A",12},{"2",13},{"joker",14},{"JOKER",15}};
enum PokerType{
    Sigle,            //单个     0
    Double,           //对子     1
    Straight,         //顺子     2
    Triple,           //三个     3
    Bomb,             //**     4
    DoubleKing        //王炸     5
};

//poker 是合法的牌,判断其是那种类型的手牌
PokerType whichType(vector<string>& poker){
    int n = poker.size();
    if(n == 1)
        return Sigle;                                     //单个
    else if(n == 2){
        if(poker[0] == "joker" || poker[0] == "JOKER")
            return DoubleKing;                                //如果为两张牌且不为大小王的话,只能是对子
        return Double;                                //否则,为王炸
    }
    else if(n == 3)
        return Triple;                                    //三张牌为三个
    else if(n == 4)
        return Bomb;                                     //四张牌为**
    else 
        return Straight;                                 //多于四张牌的为顺子
}

//比较两幅牌的大小:
//如果第一幅比第二幅牌大,返回 1
//如果第一幅牌比第二幅小的话,返回 -1
//否则,代表两副牌不可以比较,返回 0
int battle(vector<string>& poker1,vector<string>& poker2){
    PokerType t1 = whichType(poker1);
    PokerType t2 = whichType(poker2);
    if(t1 == DoubleKing)               //扑克1为王炸
        return 1;
    else if(t2 == DoubleKing)          //扑克2为王炸
        return -1;
    else if(t1 == Bomb){               //扑克1为**
        if(t2 == Bomb)
            return comp[poker1[0]] > comp[poker2[0]] ? 1 : -1;        //扑克二也为**,比较谁大谁小
        return 1;                                                     //否则,扑克1**一定大
    }
    else if(t2 == Bomb){
        //扑克二为**,而扑克1不为**
        return -1;
    }
    else if(t1 == t2){
        //两副牌既没有王炸也没有**时,两幅牌是同类型时
        if(t1 == Straight && poker1.size() != poker2.size())
            return 0;                                                //两副牌都是顺子时,但是数量不同是,则不是同类型牌,返回 0
        return comp[poker1[0]] > comp[poker2[0]] ? 1 : -1;
    }
    return 0;                                                        //不是同类型的牌,返回 0
}
int main(){
    vector<string> poker1;            //第一幅扑克牌
    vector<string> poker2;            //第二幅扑克牌
    string card;
    bool inFirstPoker = true;
    while(cin >> card){
        size_t dashPos = card.find('-');
        if(dashPos != string::npos){
            //即该字符串为两副牌的分解点
            poker1.push_back(card.substr(0,dashPos));
            poker2.push_back(card.substr(dashPos + 1));
            inFirstPoker = false;
            continue;
        }
        if(inFirstPoker)
            poker1.push_back(card);
        else
            poker2.push_back(card);
    }
    int win = battle(poker1, poker2);
    if(win == 0)
        cout << "ERROR" << endl;
    else if(win == 1){
        for(auto cd : poker1)
            cout << cd << ' ';
    }
    else if(win == -1){
        for(auto cd : poker2)
            cout << cd << ' ';
    }
    return 0;
}
使用了一种比较笨的方法解决,但是思路比较清晰,就是比较繁琐!
发表于 2021-08-10 16:58:08 回复(0)
#include <bits/stdc++.h>

using namespace std;

int main()
{
    string input;
    unordered_map<string, string> maps;
    maps["3"] = "a";
    maps["4"] = "b";
    maps["5"] = "c";
    maps["6"] = "d";
    maps["7"] = "e";
    maps["8"] = "f";
    maps["9"] = "g";
    maps["10"] = "h";
    maps["J"] = "i";
    maps["Q"] = "k";
    maps["K"] = "m";
    maps["A"] = "n";
    maps["2"] = "x";
    maps["joker"] = "y";
    maps["JOKER"] = "z";
    while (getline(cin, input))
    {
        if (input.find("joker JOKER") != -1)
        {
            cout << "joker JOKER" << endl;
            continue;
        }

        int pos = input.find("-");

        string left2 = input.substr(0, pos);
        string right2 = input.substr(pos + 1, input.size() - pos + 1);
        string left = "";
        string right = "";
        string str = "";

        for (int i = 0; i < left2.size(); ++i)
        {
            if (left2[i] != ' ')
            {
                str.push_back(left2[i]);
            }
            else
            {
                left += maps[str];
                str = "";
            }
            if (i == left2.size() - 1)
            {
                left += maps[str];
                str = "";
            }
        }
        str = "";
        for (int i = 0; i < right2.size(); ++i)
        {
            if (right2[i] != ' ')
            {
                str.push_back(right2[i]);
            }
            else
            {
                right += maps[str];
                str = "";
            }

            if (i == right2.size() - 1)
            {
                right += maps[str];
                str = "";
            }
        }


        if (left.size() == right.size())
        {
            if (left > right)
            {
                cout << left2 << endl;
            }

            else
            {
                cout << right2 << endl;
            }
        }
        else
        {
            if (left.size() == 4 && left[0] == left[1] && left[1] == left[2] && left[2] == left[3])
            {
                cout << left2 << endl;
            }
            else if (right.size() == 4 && right[0] == right[1] && right[1] == right[2] && right[2] == right[3])
            {
                cout << right2 << endl;
            }
            else
            {
                cout<<"ERROR"<<endl;
            }
            
        }
    }
    return 0;
}

// J J J J-3 3 3 3

发表于 2020-05-14 17:30:21 回复(0)
JavaScript
前排大佬的count方法太牛逼了。
var line = readline();

if (line.search('joker JOKER') != -1) {
    console.log('joker JOKER');
} else {
    var line = line.split('-');
    var hand1 = line[0].split(' '),
        hand2 = line[1].split(' ');
    if (hand1.length == hand2.length) {
        //牌数相同,谁最小牌大谁大
        if (count(hand1[0]) > count(hand2[0])) {
            console.log(hand1.join(' '));
        } else {
            console.log(hand2.join(' '));
        }
    } else {
        //牌数不同,谁有炸弹谁大
        if (hand1.length == 4) {
            console.log(hand1.join(' '));
        } else if (hand2.length == 4) {
            console.log(hand2.join(' '));
        } else {
            console.log('ERROR');
        }
    }
}

function count(cur) {
    return "345678910JQKA2jokerJOKER".indexOf(cur);
}



发表于 2020-03-08 17:53:22 回复(0)
蠢办法
size_di = {"3":1,"4":2,"5":3,"6":4,"7":5,"8":6,"9":7,"10":8,
"J":9,"Q":10,"K":11,"A":12,"2":13,"joker":14,"JOKER":15}

poker = input()
poker1,poker2 = poker.split("-")
poker1 = poker1.split()
poker2 = poker2.split()
if "joker JOKER" in poker:
    print ("joker JOKER")
elif len(poker1) == 4&nbs***bsp;len(poker2) == 4:
    if len(set(poker1)) == 1 and len(set(poker2)) == 1:
        if size_di[poker1[0]] > size_di[poker2[0]]:
            print (" ".join(poker1))
        else:
            print (" ".join(poker2))
    elif len(set(poker1)) == 1:
        print (" ".join(poker1))
    else:
        print (" ".join(poker2))

elif len(poker1) == len(poker2):
    to1 = 0
    to2 = 0
    for key in poker1:
        to1 += size_di[key]

    for key in poker2:
        to2 += size_di[key]

    if to1 > to2:
        print (" ".join(poker1))
    else:
        print (" ".join(poker2))
else:
    print ('ERROR')


编辑于 2020-02-22 20:07:38 回复(0)
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
static vector<string> POINT = {"3","4","5","6","7",
                               "8","9","10","J","Q","K", 
                               "A","2","joker","JOKER"};
int get_point(string str){
    if(str == "")return -1;
    if(str == "joker JOKER")return 100;
    vector<string> arr;
    while(str.size()>0){
        int i = str.find(" ");
        if(i>0){
            arr.push_back(str.substr(0,i));
            str.erase(0,i+1);
        }else{
            arr.push_back(str);
            str = "";
        }
    }
    int p = (int)(find(POINT.begin(), POINT.end(),arr[0]) - POINT.begin());
    return p + 20 *( arr.size() - 1);
}

int main(){
    string str;
    while(getline(cin,str)){
        int i = str.find("-");
        if(i>0){
            string str1 = str.substr(0,i);
            string str2 = str.substr(i+1);
            int a = get_point(str1);
            int b = get_point(str2);
            if(a==100||b==100)cout<<"joker JOKER"<<endl;
            else{
                int a_rank = a/20, b_rank = b/20;
                if(a_rank != b_rank){
                    if(a_rank==3)cout<<str1<<endl;
                    else if(b_rank==3)cout<<str2<<endl;
                    else cout<<"ERROR"<<endl;
                }else{
                    if(a>b)cout<<str1<<endl;
                    else cout<<str2<<endl;
                }
            }
        }
        
    }
    return 0;
}
给每个手牌计分
发表于 2020-02-16 14:34:18 回复(0)

//把题目解析完之后,可以发现,主要是进行字符串长度,首元素大小的比较

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

int main()
{
    string str;
    while(getline(cin, str))
    {
        if(str.find("joker JOKER") != -1)
        {
            cout<<"joker JOKER"<<endl;
            break;
        }
        string str1 = str.substr(0, str.find('-'));
        string str2 = str.substr(str.find('-')+1);
        string read = "345678910JQKA2";
        int count1 = count(str1.begin(),str1.end(), ' ');
        int count2 = count(str2.begin(),str2.end(), ' ');
        if(count1 == 3 && count2 != 3)
            cout<<str1<<endl;
        else if(count2 == 3 && count1 != 3)
            cout<<str2<<endl;
        else if(count1 != count2)
            cout<<"ERROR"<<endl;
        else
            if(read.find(str1[0]) > read.find(str2[0]))
                cout<<str1<<endl;
            else
                cout<<str2<<endl;
    }
    return 0;
}
发表于 2019-11-25 10:43:32 回复(0)
# python 3
# 核心思想是利用牌的长度来判断牌的类型
# 注意对10的处理,转换成X
left_,right_ = input().split('-')
left = ''.join(left_.split())
# 如果有10 ,把10 换成单个字母X表示,以方便利用长度判断牌型大小
if '1' in left:
    left= left.replace('10','X')
right =''.join(right_.split())
if '1' in right:
    right = right.replace('10','X')
# 牌面和面值 映射为字典
key=['3','4','5','6','7','8','9','X','J','Q','K','A','2']
value=[i for i in range(3,16)]
d =dict(zip(key,value))
# 长度不同则 有双王炸(长度为10)或四炸(长度为4),或单个一王(长度为5)
if len(left)!=len(right):
    if len(left)==10:
        res=left_
    elif len(right)==10:
        res = right_
    elif len(left)==4:
        res = left_
    elif len(right)==4:
        res = (right_)
    elif len(left) in (1,5) and len(right) in (1,5):
        if len(left)==5:
            res =left_
        else:
            res =right_
    # 不可比较的不同牌型,如5和55
    else:
        res ='ERROR'
# 长度相同,只要比较第一个张牌就ok
else:
    if d[left[0]]>d[right[0]]:
        res=left_
    elif d[left[0]]<d[right[0]]:
        res=right_
print(res)               
发表于 2019-09-02 17:00:19 回复(0)
import sys
while True:
    try:
        a = sys.stdin.readline().strip()
        b = a.replace('2','15').replace('joker','16').replace('JOKER','17').replace('J','11').replace('Q','12').replace('K','13').replace('A','14').split('-')
        l = list(map(int, b[0].split(' ')))
        r = list(map(int,b[1].split(' ')))
        ll = len(l)
        lr = len(r)
        list(map(int, sys.stdin.readline().strip().split()))
        if (l == [17,16] or l == [16,17]):
            re = 0
        elif (r == [17,16] or r == [16,17]):
            re = 1
        elif ll == 4 and lr == 4:
            re = int(l[0]<r[0])
        elif ll == 4 or lr == 4:
            re = 0 if ll == 4 else 1
        elif ll != lr:
            print("ERROR")
            break
        elif ll==1:
            re = int(l<r)
        elif ll == 2:
            re = int(l[0]<r[0])
        elif ll == 3:
            re = int(l[0]<r[0])
        elif ll == 5:
            re = int(l[0]<r[0])
        print(a.split('-')[re])
    except:
        break

发表于 2019-03-17 20:57:35 回复(0)
import java.util.*;

public class Main {     String s;      String s1;       String s2;          public Main(){         Scanner scan=new Scanner(System.in);         s=scan.nextLine();         int i=s.indexOf("-");           s1=s.substring(0, i);          s2=s.substring(i+1);     }     public void frun(){                  int d1=paixin(s1);         int d2=paixin(s2);         if(d1==6||d2==6){             System.out.println("joker JOKER");         }else{             if(d1==4||d2==4){                 if(d1==d2){                     bijiao();                                      }else{                     if(d1==4){                         System.out.println(s1);                     }                     if(d2==4){                         System.out.println(s2);                     }                 }             }else{                 if(d1!=d2){                     System.out.println("ERROR");                 }                 if(d1==d2){                     bijiao();                 }             }         }     }          public static void main(String[] args) {         // TODO Auto-generated method stub         new Main().frun();     }       int paixin(String ss){         int i=0;         if(ss.contains("joker")){             i=6;         }else{             int count=0,start=0;             while(ss.indexOf(" ",start)>=0&&start<ss.length()){                 count++;                 start=ss.indexOf(" ",start)+1;             }             i=count+1;         }         return i;     }       void bijiao(){             if(!(s1.startsWith("10")||s2.startsWith("10"))){                 if(s1.compareTo(s2)>0){                     System.out.println(s1);                 }else{                     System.out.println(s2);                 }             }else{                 if(s1.startsWith("10")){                     if(s2.compareTo("2")>=0&&s2.compareTo("9")<=0){                         System.out.println(s1);                     }else{                         System.out.println(s2);                     }                 }                 if(s2.startsWith("10")){                     if(s1.compareTo("2")>=0&&s1.compareTo("9")<=0){                         System.out.println(s2);                     }else{                         System.out.println(s1);                     }                 }             }       }              }

发表于 2018-04-06 13:29:23 回复(0)
#include<string>
#include<iostream>
using namespace std;
//定义单张牌面的大小顺序(在数组前面的小,后面的大)
string arr[] = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", "joker", "JOKER" };
//在main函数中通过牌面在数组中的下标比大小,该函数返回单张牌面在数组中的下标
int FindIndex(string str)
{
for (int i = 0; i < 15; i++)
if (arr[i] == str)
return i;
return 15;
}

int main()
{
char ch;
bool is1max;
int cont1 = 0, cont2 = 0;
string str1[5] = { "" }, str2[5] = { "" };
while ((ch = getchar()) != '-')//输入1手牌,并记录牌张数
{
if (ch == ' ')
cont1++;
else    
   str1[cont1] += ch;
}
cont1++;
while ((ch = getchar()) != '\n')//输入2手牌,并记录牌张数
{
if (ch == ' ')
cont2++;
else
str2[cont2] += ch;
}
cont2++;
//输出ERROR的情况:两手牌数目不等 且 两手牌中任何一手牌都不是四个或对王
if (cont1 != cont2 && (cont1 != 4 && cont2 != 4 && str1[0] != "joker" && str2[0] != "joker"))
cout << "ERROR" << endl;
else
{
if (cont1 == cont2)//数目相等比大小
{
if (FindIndex(str1[0]) > FindIndex(str2[0]))
is1max = true;
else
is1max = false;
}
else//数目不等,两手牌中至少有一个是四个或对王
{
if ((cont1 == 2 && str1[0] == "joker") || (cont1 == 4 && !(cont2 == 2 && str2[0] == "joker")))
is1max = true;
else
is1max = false;
}
if (is1max)//输出
{
for (int i = 0; i < cont1; i++)
{
cout << str1[i];
if (i < cont1 - 1) cout << " ";
}
}
else
{
for (int i = 0; i < cont2; i++)
{
cout << str2[i];
if (i < cont2 - 1) cout << " ";
}
}
}
return 0;
}
发表于 2017-06-24 01:25:44 回复(0)
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
#include <regex>
using namespace std;
map<int,int> rate;
void initMap(){
    for(int i=3;i<=10;i++)
        rate[i+48]=i;
    rate[74]=11;
    rate[81]=12;
    rate[75]=13;
    rate[65]=14;
    rate[50]=15;
    rate[48]=10;
}
string Judge(string left,string right){
    if(left==""||right=="") return "";
    if(left=="joker JOKER"||right=="joker JOKER") return "joker JOKER";
    vector<char> lv;
    vector<char> rv;
    for(int i=1;i<=left.size();i++)
        if(left[i]==' '||i==left.size()){
            lv.push_back(left[i-1]);
        }
    for(int i=1;i<=right.size();i++)
        if(right[i]==' '||i==right.size()){
            rv.push_back(right[i-1]);
        }
    if(lv.size()==rv.size()){
        return rate[lv[0]]>rate[rv[0]]?left:right;
    }
    if(lv.size()==4&&rv.size()!=4){
        return left;
    }else if(lv.size()!=4&&rv.size()==4){
        return right;
    }
    return "ERROR";
}
int main(){
    string input;
    initMap();
    getline(cin,input);
    int f=input.find('-');
    string left=input.substr(0,f);
    string right=input.substr(f+1);
    cout<<Judge(left,right);
    return 0;

}

发表于 2017-02-13 15:37:07 回复(0)
/*
解题思想:
1.无论两方任意一方有人拿到joker JOKER或JOKER joker都认为其是胜利方。
2.如果没有人拿到大小王,就对每个人的牌进行判断:
(1)两个人的牌数一样多,在扑克牌数组中进行位置查找,如果哪一付手牌的位置靠后说明其牌大,
(因为根据题目规则,两个人的牌只有个子,对子,顺子,三个,**,和王这几种情况,所以越靠后说明牌越大)
  否则说明牌小。
(2)两个人的牌数不一样多,其中有一个人的牌的空格数是3,说明他的牌是**,例如4 4 4 4有三个空格
和其他牌可以比较的只有**和王,又因为两个人的牌数不一样多,而且有一个人的牌是**,说明**是胜利
*/
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#define PrintS1 {cout << s1 << endl;return 0;}
#define PrintS2 {cout << s2 << endl;return 0;}
int count(string & str)
{
    int n = 0;
    string::size_type  i = 0 , k=0;    //find函数的返回值是整数,假如字符串存在包含关系,其返回值必定不等于npos,但如果字符串不存在包含关系,那么返回值就一定是npos
    while ((k=str.find(' ',i)) != string::npos)//npos是一个常数一般是指不存在的位置,
    {
        n++;
        i = k + 1;
    }
    return n;
}
int main()
{
    string input;
    getline(cin,input);
    string s1,s2;
    int t = input.find('-');//查找'-'在input中的位置t
    s1 = input.substr(0, t);//取s1为从0-t的子串
    s2 = input.substr(t + 1);//取s2为从t+1之后的子串
    int n1 = count(s1);//count函数返回该字符串敏感词有几张牌
    int n2 = count(s2);
    string POKER = "345678910JQKA2jokerJOKER";
    vector<string> MAX;
    MAX.push_back("joker JOKER");
    MAX.push_back("JOKER joker");//最大的牌是MAX
    if (s1 == MAX[0] || s1 == MAX[1]) PrintS1
if (s2 == MAX[0] || s2 == MAX[1]) PrintS2
if (n1==n2)
{
string f1, f2;
string::size_type k;
k = s1.find(' ');
f1 = s1.substr(0, k);
k = s2.find(' ');
f2 = s2.substr(0, k);
if (POKER.find(f1) > POKER.find(f2)) PrintS1
PrintS2
}
    if (n1 == 3 && n2 != 3) PrintS1
if (n2 == 3 && n1 != 3) PrintS2
cout << "ERROR" << endl;
}

发表于 2017-02-09 11:20:57 回复(0)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
//类型 个子 0 对子 1 三子 2 炸弹 3 顺子 4 王炸 也属于炸弹的范畴
//各类型大小 3-17 3 - joker
struct poker{
    char real[20];
    int type;
    int value;
    void init(char* cards){
        strcpy(real, cards);
        size_t len = strlen(cards);
        if(cards[0] == 'j' || cards[0] == 'J'){
            //说明是王
            if(len == 5){
                type = 0;
                value = cards[0] == 'j' ? 16 : 17;
            }else{
                type = 3;
                value = 17;
            }
        }else{
            //不是王
            if(cards[0] == '1'){
                //说明10开始
                switch(len){
                    case 2:type = 0;break;
                    case 5:type = 1;break;
                    case 8:type = 2;break;
                    case 11:type = 3;break;
                    case 10:type = 4;break;
                }
                value = 10;
            }else{
                switch(len){
                    case 1:type = 0;break;
                    case 3:type = 1;break;
                    case 5:type = 2;break;
                    case 7:type = 3;break;
                    default:type = 4;break;
                }
                switch(cards[0]){
                    case 'J':value = 11;break;
                    case 'Q':value = 12;break;
                    case 'K':value = 13;break;
                    case 'A':value = 14;break;
                    case '2':value = 15;break;
                    default:value = cards[0]-'0';break;
                }
            }
        }
        if(type == 3){
            value += 20;
        }
    }
};
int main(){
    char str[30];
    struct poker poker1,poker2;
    while(gets(str)){
        size_t len = strlen(str);
        for(int i = 0;i<len;i++){
            if(str[i] == '-'){
                str[i] = 0;
                poker1.init(str);
                poker2.init(&str[i+1]);
                break;
            }
        }
        if(poker1.type == poker2.type || poker1.type == 3 || poker2.type == 3){
            if(poker1.value > poker2.value){
                printf("%s\n",poker1.real);
            }else{
                printf("%s\n",poker2.real);
            }
        }else{
            puts("ERROR");
        }
    }
}
发表于 2016-08-25 18:21:15 回复(0)
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
	string card = "345678910JQKA2";
	string str;
	vector<string> MAX;
	MAX.push_back("joker JOKER");
	MAX.push_back("JOKER joker");
	MAX.push_back("joker");
	MAX.push_back("JOKER");
	while (getline(cin,str)){
		int t = str.find("-");
		string LEFT = str.substr(0, t);
		string RIGHT = str.substr(t + 1);

		int LEFT_NUM = count(LEFT.begin(), LEFT.end(), ' ');
		int RIGHT_NUM = count(RIGHT.begin(), RIGHT.end(), ' ');
		/* 判断是否有对大小王 Start*/
		if (LEFT == MAX[0] || LEFT == MAX[1])
		{
			cout << LEFT << endl;
			continue;
		}
		if (RIGHT == MAX[0] || RIGHT == MAX[1])
		{
			cout << RIGHT << endl;
			continue;
		}
		if (LEFT == MAX[2] || LEFT == MAX[3])
		{
			if (RIGHT_NUM == 0){
				cout << LEFT << endl;
				continue;
			}
			else
			{
				cout << "ERROR" << endl;
				continue;
			}
		}
		if (RIGHT == MAX[2] || RIGHT == MAX[3])
		{
			if (LEFT_NUM == 0){
				cout << RIGHT << endl;
				continue;
			}
			else
			{
				cout << "ERROR" << endl;
				continue;
			}
		}
		/* 判断是否有个、对大小王 END*/
		/*
			有个问题
			就是10是两位的,所以查找的时候如果第一张牌是10,找的只是1
			还好没有1*这样的其他数字了,所以这个方法还是可以的
			*/

		//顺子(5张牌),对子(2张牌),三子(3张牌)
		if (LEFT_NUM == RIGHT_NUM){//输入个数相同(中间的空格数量一样),就进行比较
			if (LEFT_NUM >= 4 && RIGHT_NUM >= 4)//顺子
			{
				int LEFT_INDEX = card.find(LEFT[0]);//题目中已经说了已经排好序,所以就是直接比较第一位
				int RIGHT_INDEX = card.find(RIGHT[0]);
				string max = LEFT_INDEX > RIGHT_INDEX ? LEFT : RIGHT;
				cout << max << endl;
				continue;
			}
			if (LEFT_NUM == 2 && RIGHT_NUM == 2)//三子
			{
				int LEFT_INDEX_NUM = count(LEFT.begin(), LEFT.end(), LEFT[0]);
				int RIGHT_INDEX_NUM = count(RIGHT.begin(), RIGHT.end(), RIGHT[0]);
				if (LEFT_INDEX_NUM == 3 && LEFT_INDEX_NUM == 3)
				{
					int LEFT_INDEX = card.find(LEFT[0]);
					int RIGHT_INDEX = card.find(RIGHT[0]);
					string max = LEFT_INDEX > RIGHT_INDEX ? LEFT : RIGHT;
					cout << max << endl;
					continue;
				}
				else{
					cout << "ERROR" << endl;
					continue;
				}
			}
			if (LEFT_NUM == 1 && RIGHT_NUM == 1)//对子
			{
				int LEFT_INDEX_NUM = count(LEFT.begin(), LEFT.end(), LEFT[0]);
				int RIGHT_INDEX_NUM = count(RIGHT.begin(), RIGHT.end(), RIGHT[0]);
				if (LEFT_INDEX_NUM == 2 && LEFT_INDEX_NUM == 2)
				{
					int LEFT_INDEX = card.find(LEFT[0]);
					int RIGHT_INDEX = card.find(RIGHT[0]);
					string max = LEFT_INDEX > RIGHT_INDEX ? LEFT : RIGHT;
					cout << max << endl;
					continue;
				}
				else{
					cout << "ERROR" << endl;
					continue;
				}
			}
			if (LEFT_NUM == 0 && RIGHT_NUM == 0)//单个比对
			{
				int LEFT_INDEX = card.find(LEFT[0]);
				int RIGHT_INDEX = card.find(RIGHT[0]);
				string max = LEFT_INDEX > RIGHT_INDEX ? LEFT : RIGHT;
				cout << max << endl;
				continue;
			}
		}
		//炸弹对比
		if (LEFT_NUM == 3 && RIGHT_NUM != 3)
		{
			cout << LEFT << endl;
			continue;
		}
		if (LEFT_NUM != 3 && RIGHT_NUM == 3)
		{
			cout << RIGHT << endl;
			continue;
		}
		if (LEFT_NUM == 3 && RIGHT_NUM == 3)
		{
			int LEFT_INDEX_NUM = count(LEFT.begin(), LEFT.end(), LEFT[0]);
			int RIGHT_INDEX_NUM = count(RIGHT.begin(), RIGHT.end(), RIGHT[0]);
			if (LEFT_INDEX_NUM == 4 && RIGHT_INDEX_NUM == 4)
			{
				int LEFT_INDEX = card.find(LEFT[0]);
				int RIGHT_INDEX = card.find(RIGHT[0]);
				string max = LEFT_INDEX > RIGHT_INDEX ? LEFT : RIGHT;
				cout << max << endl;
				continue;
			}
			if (LEFT_INDEX_NUM == 4 && RIGHT_INDEX_NUM != 4)
			{
				cout << LEFT << endl;
				continue;
			}
			if (LEFT_INDEX_NUM != 4 && RIGHT_INDEX_NUM == 4)
			{
				cout << RIGHT << endl;
				continue;
			}
		}
		cout << "ERROR" << endl;
	}
	return 0;
}

发表于 2016-08-03 11:27:27 回复(2)
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication6
{
    class Program
    {
        static int getCardSize(string str)
        {
            return "345678910JQKA2jokerJOKER".IndexOf(str);
        }
        static void Main(string[] args)
        {
            //我们可以先将牌按照大小进行规则化,总共15张
            string str = Console.ReadLine();
            string[] split = str.Split(new string[]{"-"},StringSplitOptions.RemoveEmptyEntries);
            string[] left = split[0].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            string[] right = split[1].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            int sizeLeft = left.Length,sizeRight=right.Length;
            if(sizeLeft==sizeRight)
            {
                //张数相同
                if (getCardSize(left[0]) > getCardSize(right[0]))
                {
                    Console.WriteLine(split[0]);
                }
                else
                    Console.WriteLine(split[1]);
            }
            else
            {
                //张数不同
                //先假设左边为1,2,3,4,5比较右边不同张数时的情形
                if(sizeLeft==1)
                {
                    if(sizeRight==2)
                    {
                        if(right[0]==right[1])
                            Console.WriteLine("ERROR");
                        else
                            Console.WriteLine(split[1]);
                    }
                    else if(sizeRight==3 || sizeRight==5)
                    {
                        Console.WriteLine("ERROR");
                    }
                    else if(sizeRight==4)
                    {
                        Console.WriteLine(split[1]);
                    }
                }
                else if(sizeLeft==2)
                {
                    if (sizeRight == 1)
                    {
                        if (left[0] == left[1])
                            Console.WriteLine("ERROR");
                        else
                            Console.WriteLine(split[0]);
                    }
                    else if (sizeRight == 3 || sizeRight == 5)
                    {
                        if (left[0] == left[1])
                            Console.WriteLine("ERROR");
                        else
                            Console.WriteLine(split[0]);
                    }
                    else if (sizeRight == 4)
                    {
                        if (left[0] == left[1])
                        {
                            Console.WriteLine(split[1]);
                        } 
                        else
                            Console.WriteLine(split[0]);
                    }
                }
                else if (sizeLeft == 3)
                {
                    if (sizeRight == 1 || sizeRight == 5)
                    {
                        Console.WriteLine("ERROR");
                    }
                    else if (sizeRight == 2)
                    {
                        if (right[0] == right[1])
                            Console.WriteLine("ERROR");
                        else
                            Console.WriteLine(split[1]);
                    }
                    else if (sizeRight == 4)
                    {
                         Console.WriteLine(split[1]);
                    }
                }
                else if (sizeLeft == 4)
                {
                    if (sizeRight == 1 || sizeRight==3 || sizeRight == 5)
                    {
                        Console.WriteLine(split[0]);
                    }
                    else if (sizeRight == 2)
                    {
                        if (right[0] == right[1])
                            Console.WriteLine(split[0]);
                        else
                            Console.WriteLine(split[1]);
                    }
                }
                else if (sizeLeft == 5)
                {
                    if (sizeRight == 1 || sizeRight == 3)
                    {
                        Console.WriteLine("ERROR");
                    }
                    else if (sizeRight == 2)
                    {
                        if (right[0] == right[1])
                            Console.WriteLine("ERROR");
                        else
                            Console.WriteLine(split[1]);
                    }
                    else if (sizeRight == 4)
                    {
                        Console.WriteLine(split[1]);
                    }
                }
            }
        }
    }
}

发表于 2015-09-07 18:53:42 回复(0)
//提交了好几次终于通过了。 
//第一次没通过是因为: 直接把子串的第一个字符作为value,
//比如"1 1 1 1"的val为1,但是遇到像 "J, J, J"这样的就错了, 解决方法是使用map
//第二次没通过是因为:使用map 把char 映射为 int 没考虑到”10“不是char,所以需要改为string
//第三次没通过是因为:spaceCount 转换到 enum Type时 对spaceCount+1了, 这里不+1刚刚好。(enum从0计数)
//粘一下我的代码。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <sstream>
using namespace std;
class Pai
{
 public:
 enum Type{One, Two, Three, Four, Five, Joker};
 Pai(string _str) : str(_str)
 {
 if (str[0] == 'j') type = Joker; //第一个字符是'j',一定是Joker
 else
 {
 string sVal;
 sVal = str.substr(0, str.find(' '));
 val = m[sVal];
 int spaceCount = 0;
 for (auto &e : str)
 if (e == ' ') ++spaceCount;
 type = static_cast<Type>(spaceCount);
 }
 }
 string to_str() const
 {return str;}
 bool comparable(const Pai& b) const
 {
 if (type == Joker || b.type == Joker ||
 type == Four || b.type == Four || type == b.type) return true;
 else
 return false;
 }
 bool operator< (const Pai& p) const
 {
 if (type == p.type) return val < p.val;
 else if (type == Joker) return false;
 else if (p.type == Joker) return true;
 else if (type == Four) return false;
 else if (p.type == Four) return true;
 }
 static unordered_map<string, int> m;
 string str;
 Type type;
 int val; //min value for five.
};
unordered_map<string, int> Pai::m{
 {"A", 1},
 {"2", 2},
 {"3", 3},
 {"4", 4},
 {"5", 5},
 {"6", 6},
 {"7", 7},
 {"8", 8},
 {"9", 9},
 {"10", 10},
 {"J", 11},
 {"Q", 12},
 {"K", 13},
};
int main()
{
 string line;
 while (getline(cin, line))
 {
 string pai_a = line.substr(0, line.find('-'));
 string pai_b = line.substr(line.find('-') + 1);
 Pai a(pai_a), b(pai_b);
 if (!a.comparable(b)) cout << "ERROR" << endl;
 else
 {
 if (a < b) cout << b.to_str();
 else
 cout << a.to_str();
 cout << endl;
 }
 }
}
 
发表于 2015-08-25 17:15:37 回复(2)
//“输入每手牌可能是个子,对子,顺子(连续5张),三个,炸弹(四个)和对王中的一种,
//不存在其他情况,由输入保证两手牌都是合法的,顺子已经从小到大排列“
//这句规则让牌面类型的确定和大小的比较直接可以转换为牌个数的比较了,这是解决测试问题的捷径!
//所以一定要善于利用题目已知条件!!!
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
	string line;
	while(getline(cin,line)){
		if(line.find("joker JOKER")!=-1)
			cout<<"joker JOKER"<<endl;
		else{
			int dash=line.find('-');
			string car1=line.substr(0,dash);
			string car2=line.substr(dash+1);
			int c1=count(car1.begin(),car1.end(),' ');
			int c2=count(car2.begin(),car2.end(),' ');
			string first1=car1.substr(0,car1.find(' '));
			string first2=car2.substr(0,car2.find(' '));
			string str="345678910JQKA2jokerJOKER";
			if(c1==c2){
				if(str.find(first1)>str.find(first2))
					cout<<car1<<endl;
				else
					cout<<car2<<endl;
			}else 
				if(c1==3)
					cout<<car1<<endl;
				else if(c2==3)
					cout<<car2<<endl;
				else
					cout<<"ERROR"<<endl;
		}
	}
}

编辑于 2016-08-31 11:24:00 回复(52)
def isBomb( poker_value,first,length,poker_dict):
    if not first+3<length:
        return 0
    bomb= poker_value[first]
    for i in range(first+1,first+4):
        if  poker_value[i]!=bomb:
            return 0
    poker_dict.append(("bomb",bomb))
    return 1

def isPlane( poker_value,first,length,poker_dict):
    if not first+2<length:
        return 0
    plane= poker_value[first]
    for i in range(first+1,first+4):
        if  poker_value[i]!=plane:
            return 0
    poker_dict.append(("plane",plane))
    return 1

def isPair( poker_value,first,length,poker_dict):
    if not first+1<length:
        return 0
    pair= poker_value[first]
    if pair!= poker_value[first+1]:
        return 0
    poker_dict.append(("pair",pair))
    return 1
def isStraight( poker_value,first,length,poker_dict):
    if not first+4<length:
        return 0
    straight= poker_value[first]
    base=straight+1
    for i in range(first+1,first+5):
        if not base== poker_value[i]:
            return 0
        base=base+1
    poker_dict.append(("straight",straight))
    return 1
        
def isKing( poker_value,first,length,poker_dict):
    if not first+1<length:
        return 0
    kings=[13,14]
    if poker_value[first] in kings and poker_value[first+1] in kings:
        poker_dict.append(("king",1))
        return 1
    return 0

def getType(poker):
    poker_list=poker.split(' ')
    length=len(poker_list)  
    keys=["3","4","5","6","7","8","9","10","J","Q","K","A","2","joker","JOKER" ]
    poker_map={}
    num=0
    for k in keys:
        poker_map[k]=num
        num+=1    
    poker_value=[]
    for p in poker_list:
        poker_value.append(poker_map[p])
    poker_dict=[]
    index=0
    if isStraight( poker_value,index,length,poker_dict):
        return poker_dict
    elif  isBomb( poker_value,index,length,poker_dict):
        return poker_dict            
    elif isPlane( poker_value,index,length,poker_dict):
        return poker_dict
    elif isKing( poker_value,index,length,poker_dict):
        return poker_dict
    elif isPair( poker_value,index,length,poker_dict):
        return poker_dict
    else:
        poker_dict.append(('single', poker_value[index]))
        return poker_dict
    
def ComparePoker(poker_a, poker_b):
    type_a=poker_a[0][0]
    type_b=poker_b[0][0]
    if type_a==type_b:
        if poker_a[0][1]>poker_b[0][1]:
            return 1
        else:
            return 2
    elif type_a=='king' or type_b=='king':
        if type_a=='king':
            return 1
        else:
            return 2
    elif  type_a=='bomb' or type_b=='bomb':
        if type_a=='bomb':
            return 1
        else:
            return 2
    else:
        return -1

if __name__=='__main__':
    poker=raw_input()
    poker_a=getType(poker.split('-')[0])
    poker_b=getType(poker.split('-')[1])    
    res=ComparePoker(poker_a, poker_b)
    if res==1:
        print poker.split('-')[0]
    elif  res==2:
        print poker.split('-')[1]
    else:
        print 'ERROR'
  

编辑于 2015-08-26 11:23:12 回复(3)