POJ - 2996 - Help Me with the Game - [模拟中的自定义排序技巧]

简体.

题目链接

这个题目,读入一个棋盘,按照一定顺序输出所有棋子的位置.

其核心方法就是: 人肉为每个棋子的名字赋一个值.用这个值来比较大小.

还有,书写cmp函数的方法也很值得回味.好题.

代码如下:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<cstring>
#include<stack>
const int maxn = 1e2+7;
using namespace std;
char analyse(string t){
    char re = 0;
    for(int i = 0;i<t.size();i++){
        if(t[i]>='a' && t[i]<='z'){
            re = t[i];
        }else if(t[i]>='A' && t[i]<='Z'){
            re = t[i];
        }
    }
    return re;
}
char grid[9][9];
int mmp[200];
bool cmp(string a,string b){
    if(a[0] == b[0]){
        if(a[2] == b[2]){
            return a[1]<b[1];
        }else{
            if(a[0]>='a'&&a[0]<='z'){
                return a[2]>b[2];
            }else{
                return a[2]<b[2];
            }
        }
    }else return mmp[a[0]]<mmp[b[0]];
}
void print(vector<string> s){
    sort(s.begin(),s.end(),cmp);
    for(int i = 0;i<s.size();i++){
        if(s[i][0]<='z'&&s[i][0]>='a'){
            s[i][0]+='A'-'a';
        }
        if(s[i][0] == 'P'){
            s[i] = s[i].substr(1);
        }
        cout << s[i] << ",\n"[i==s.size()-1];
    }
}
int main(){
#ifdef LOCAL
    freopen("in.txt","r",stdin);
#endif
    ios::sync_with_stdio(0);
    mmp['K']=1,
        mmp['Q']=2,
        mmp['R']=3,
        mmp['B']=4,
        mmp['N']=5,
        mmp['P']=6;
    mmp['k']=1,
        mmp['q']=2,
        mmp['r']=3,
        mmp['b']=4,
        mmp['n']=5,
        mmp['p']=6;

    string s;
    vector<string> wh,bl;
    for(int i = 8;i>=1;i--){
        getline(cin,s);
        if(s[0] == '+'){
            i++;
            continue;
        }
        for(int j = 0;4*j<s.size();j++){
            grid[i][j+1]=analyse(s.substr(4*j,4));
            if(grid[i][j+1]){
                string temp;
                temp+=grid[i][j+1];
                temp+=char(j+'a');
                temp+=char(i+'0');
                if(grid[i][j+1]>='a'&&grid[i][j+1]<'z'){
                    bl.push_back(temp);
                }else if(grid[i][j+1]){
                    wh.push_back(temp);
                }
            }
        }
    }
    cout << "White: ";
    print(wh);
    cout << "Black: ";
    print(bl);
}

猜你喜欢

转载自blog.csdn.net/lanadeus/article/details/77388281