[Topcoder] SRM197

divII lev2

 

先定义八个方向的偏移。取数组pieces第一对坐标,得到其八个偏移坐标,结果肯定是这些坐标的子集,所以对这八个坐标进行检醒,如果坐标对数组其它坐标都形成威胁,则加入结果数组。题目要求排好序,只要定义偏移时按有序排列就行,这样省得显式排序了。

#include <iostream> #include <string> #include <vector> #include <cmath> #include <sstream> #include <iterator> using namespace std; #define ABS(x) ( x < 0 ? -x : x) const int xoffset[8] = {-2, -2, -1, -1, 1, 1, 2, 2}; const int yoffset[8] = {-1, 1, -2, 2, -2, 2, -1, 1}; class GeneralChess { private: int canThreaten(const int curx, const int cury, const int posx, const int posy) { if (ABS(curx - posx) == 1 && ABS(cury - posy) == 2 || ABS(curx- posx) == 2 && ABS(cury - posy) == 1) return 1; else return 0; } public: vector<string> attackPositions(vector<string> pieces) { vector<string> res; int x, y; char t; istringstream ss(pieces.at(0)); ss >> x >> t >> y; for (int i = 0; i < 8; i++) { int curx = x + xoffset[i]; int cury = y + yoffset[i]; int j = 1; for (j = 1; j < pieces.size(); j++) { istringstream oss(pieces.at(j)); int posx, posy; oss >> posx >> t >> posy; if (!canThreaten(curx, cury, posx, posy)) { break; } } if (j == pieces.size()) { ostringstream ress; ress << curx << ',' << cury; res.push_back(ress.str()); } } return res; } }; int main() { GeneralChess gc; vector<string> vec; vec.push_back("0,0"); vector<string> res = gc.attackPositions(vec); copy(res.begin(), res.end(), ostream_iterator<string>(cout, " ")); cout << endl; vec.clear(); vec.push_back("2,1"); vec.push_back("-1,-2"); res = gc.attackPositions(vec); copy(res.begin(), res.end(), ostream_iterator<string>(cout, " ")); cout << endl; return 0; }

当然,如果硬要显式排序,也可以:

bool compare(string a, string b) { int ax, ay; int bx, by; char t; istringstream ss(a); ss >> ax >> t >> ay; ss.clear(); ss.str(b); ss >> bx >> t >> by; if (ax < bx || ax == bx && ay < by) return true; else return false; } int main() { vector<string> vec; vec.push_back("0,0"); vec.push_back("2,1"); vec.push_back("1,2"); sort(vec.begin(), vec.end(), compare); copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, " ")); cout << endl; return 0; }

你可能感兴趣的:([Topcoder] SRM197)