大致题意是输入一个象棋的类似棋谱,然后按要求输出棋子的位置,白棋行小的先输出,黑棋行大的先输出,相同行的列小的先输出.
+---+---+---+---+---+---+---+---+
|.r.|:::|.b.|:q:|.k.|:::|.n.|:N:|
+---+---+---+---+---+---+---+---+
|:p:|.p.|:p:|.Q.|:p:|.R.|:::|.p.|
+---+---+---+---+---+---+---+---+
|...|:::|.N.|:::|...|:::|...|:p:|
+---+---+---+---+---+---+---+---+
|:::|...|:::|.K.|:::|...|:::|.K.|
+---+---+---+---+---+---+---+---+
|...|:::|...|:::|.P.|:::|...|:P:|
+---+---+---+---+---+---+---+---+
|:P:|...|:::|...|:::|...|:::|...|
+---+---+---+---+---+---+---+---+
|.N.|:::|.P.|:P:|...|:P:|.r.|:P:|
+---+---+---+---+---+---+---+---+
|.p.|.N.|:B:|.Q.|:K:|.B.|:::|.R.|
+---+---+---+---+---+---+---+---+
White: Ke1,Qd1,Ra1,Rh1,Bc1,Bf1,Nb1,a2,c2,d2,f2,g2,h2,a3,e4
Black: Ke8,Qd8,Ra8,Rh8,Bc8,Ng8,Nc6,a7,b7,c7,d7,e7,f7,h7,h6**
基本思路:这个题是一个基本的模拟题目,没有什么算法难度,但是比较麻烦.我采取的办法是利用队列和栈进行读取数据,对于黑棋用队列来存取,对于白棋用栈来存取.注意好读取的顺序,然后输出即可.这样就可以达到题目要求的顺序,而且逻辑很清楚,不容易出错.当然要注意的就是那些+-|符号的干扰了.这个代码利用pair结构还可以大大的精简。
#include "stdafx.h"
#include "iostream"
#include "string"
#include "vector"
#include "stack"
#include "queue"
using namespace std;
const string emp("");
const char Row[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
struct Record
{
char name;
int row;
char col;
};
vector<stack<Record>> pos(6);
vector<queue<Record>> bpos(6);
void Process(string s, int line)
{
for (int i = s.size() - 1; i != -1; --i)
{
Record temp;
temp.col = Row[(i - 2) / 4], temp.row = line;
if (i % 4 == 2 && isupper(s[i]))
{
temp.name = s[i]=='P'?'\0':s[i];
switch (s[i])
{
case 'K': pos[0].push(temp); break;
case 'Q': pos[1].push(temp); break;
case 'R': pos[2].push(temp); break;
case 'B': pos[3].push(temp); break;
case 'N': pos[4].push(temp); break;
case 'P': pos[5].push(temp); break;
}
}
}
for (int i = 0; i != s.size(); ++i)
{
Record temp;
temp.col = Row[(i - 2) / 4], temp.row = line;
if (i % 4 == 2 && islower(s[i]))
{
temp.name = s[i] == 'p' ? '\0' : s[i];
switch (s[i])
{
case 'k': bpos[0].push(temp); break;
case 'q': bpos[1].push(temp); break;
case 'r': bpos[2].push(temp); break;
case 'b': bpos[3].push(temp); break;
case 'n': bpos[4].push(temp); break;
case 'p': bpos[5].push(temp); break;
}
}
}
}
int main()
{
string s1,s;
for (int line = 17;line!=0 ;--line)
{
cin >> s;
if (!(line%2))
Process(s, line/2);
}
cout << "White: ";
for (int i = 0; i != pos.size();i++)
{
stack<Record> it = pos[i];
while (!it.empty())
{
cout << it.top().name <<it.top().col<<it.top().row;
it.pop();
if (!(it.empty()&&i == pos.size()-1))
cout << ",";
}
}
cout << "\nBlack: ";
for (int i = 0; i!= bpos.size();i++)
{
queue<Record> it = bpos[i];
while (!it.empty())
{
cout << it.front().name << it.front().col << it.front().row;
it.pop();
if (!(it.empty()&&i == bpos.size()-1))
cout << ",";
}
}
return 0;
}