poj2996

本题是简单的模拟,使用双层vector嵌套存储棋子的位置和种类,然后分别对每个vector进行排序

注意:排序方法为sort(piece[i].begin(), piece[i].end(), cmpWhite);
当然,cmpWhite是比较函数,可以不加比较函数,只用用前两个参数。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include<algorithm>
using namespace std;

const int maxn = 9;

int getid[150];

struct Piece
{
	int x, y, d;
	Piece()
	{
	}
	Piece(int xx, int yy, char dd) :
		x(xx), y(yy), d(dd)
	{
	}
};

vector<vector<Piece> > piece(12);

void init()
{
	string st;

	memset(getid, -1, sizeof(getid));
	getid[int('K')] = 0;
	getid[int('Q')] = 1;
	getid[int('R')] = 2;
	getid[int('B')] = 3;
	getid[int('N')] = 4;
	getid[int('P')] = 5;
	getid[int('k')] = 6;
	getid[int('q')] = 7;
	getid[int('r')] = 8;
	getid[int('b')] = 9;
	getid[int('n')] = 10;
	getid[int('p')] = 11;
	for (int i = 1; i < maxn; i++)
	{
		getline(cin, st);
		for (int j = 1; j < maxn; j++)
		{
			char ch;
			getchar();
			getchar();
			cin >> ch;
			getchar();
			if (getid[int(ch)] != -1)
				piece[getid[int(ch)]].push_back(Piece(9 - i, j, ch));
		}
		getline(cin, st);
	}
}

bool cmpWhite(const Piece &a, const Piece &b)
{
	if (a.x == b.x)
		return a.y < b.y;
	return a.x < b.x;
}

bool cmpBlack(const Piece &a, const Piece &b)
{
	if (a.x == b.x)
		return a.y < b.y;
	return a.x > b.x;
}

void sortout()
{
	for (int i = 0; i < 6; i++)
		sort(piece[i].begin(), piece[i].end(), cmpWhite);
	for (int i = 6; i < 12; i++)
		sort(piece[i].begin(), piece[i].end(), cmpBlack);
}

void output()
{
	bool first = true;

	cout << "White: ";
	for (int i = 0; i < 6; i++)
	{
		for (unsigned int j = 0; j < piece[i].size(); j++)
		{
			if (first)
				first = false;
			else
				cout << ",";
			if (piece[i][j].d != 'P')
				cout << char(piece[i][j].d);
			cout << char(piece[i][j].y + 'a' - 1) << piece[i][j].x;
		}
	}

	cout << endl;
	first = true;
	cout << "Black: ";
	for (int i = 6; i < 12; i++)
	{
		for (unsigned int j = 0; j < piece[i].size(); j++)
		{
			if (first)
				first = false;
			else
				cout << ",";
			if (piece[i][j].d != 'p')
				cout << char(piece[i][j].d - 'a' + 'A');
			cout << char(piece[i][j].y + 'a' - 1) << piece[i][j].x;
		}
	}
}

int main()
{
	//freopen("D:\\t.txt", "r", stdin);
	init();
	sortout();
	output();
	return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/1948676.html