[Topcoder] SRM197
2010-07-19 20:02
573 查看
divII lev2
先定义八个方向的偏移。取数组pieces第一对坐标,得到其八个偏移坐标,结果肯定是这些坐标的子集,所以对这八个坐标进行检醒,如果坐标对数组其它坐标都形成威胁,则加入结果数组。题目要求排好序,只要定义偏移时按有序排列就行,这样省得显式排序了。
当然,如果硬要显式排序,也可以:
先定义八个方向的偏移。取数组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 srm 325 div1
- topcoder srm 415 div1
- 【topcoder SRM 652 DIV2 250】ValueOfString
- topcoder srm 445 div1
- topcoder srm 490 div1
- topcoder srm 510 div1
- 小朋友学TopCoder(5):SRM144 DIV1 550-point
- [DP] Topcoder SRM 552 DIV1 Hard. HolyNumbers
- topcoder srm 520 div1
- [DP 博弈] Topcoder SRM579 Div1. RockPaperScissors
- topcoder srm 600 div1
- Topcoder SRM 616 Div2 1000 TwoLLogo
- Topcoder SRM 701 Div2
- Topcoder SRM 559 ToyTrain
- topcoder srm 707 div1
- topcoder srm 708 div1 -3
- topcoder srm 710 div1 -23
- topcoder srm 695 div1 -3
- topcoder srm 687 div1
- topcoder srm 680 div1 -3