divII lev2
先定義八個方向的位移。取數組pieces第一對座標,得到其八個位移座標,結果肯定是這些座標的子集,所以對這八個座標進行檢醒,如果座標組數組其它座標都形成威脅,則加入結果數組。題目要求排好序,只要定義位移時按有序排列就行,這樣省得顯式排序了。
#include <iostream><br />#include <string><br />#include <vector><br />#include <cmath><br />#include <sstream><br />#include <iterator><br />using namespace std;</p><p>#define ABS(x)( x < 0 ? -x : x)</p><p>const int xoffset[8] = {-2, -2, -1, -1, 1, 1, 2, 2};<br />const int yoffset[8] = {-1, 1, -2, 2, -2, 2, -1, 1};</p><p>class GeneralChess {<br />private:</p><p>int canThreaten(const int curx, const int cury,<br /> const int posx, const int posy) {<br />if (ABS(curx - posx) == 1 && ABS(cury - posy) == 2<br />|| ABS(curx- posx) == 2 && ABS(cury - posy) == 1)<br />return 1;<br />else<br />return 0;<br />}</p><p>public:<br />vector<string> attackPositions(vector<string> pieces) {<br />vector<string> res;<br />int x, y;<br />char t;</p><p>istringstream ss(pieces.at(0));<br />ss >> x >> t >> y;</p><p>for (int i = 0; i < 8; i++) {<br />int curx = x + xoffset[i];<br />int cury = y + yoffset[i];<br />int j = 1;<br />for (j = 1; j < pieces.size(); j++) {<br />istringstream oss(pieces.at(j));<br />int posx, posy;<br />oss >> posx >> t >> posy;<br />if (!canThreaten(curx, cury, posx, posy)) {<br />break;<br />}</p><p>}<br />if (j == pieces.size()) {<br />ostringstream ress;<br />ress << curx << ',' << cury;<br />res.push_back(ress.str());<br />}<br />}<br />return res;<br />}<br />};</p><p>int main()<br />{<br />GeneralChess gc;<br />vector<string> vec;<br />vec.push_back("0,0");</p><p>vector<string> res = gc.attackPositions(vec);</p><p>copy(res.begin(), res.end(),<br /> ostream_iterator<string>(cout, " "));<br />cout << endl;</p><p>vec.clear();<br />vec.push_back("2,1");<br />vec.push_back("-1,-2");<br />res = gc.attackPositions(vec);<br />copy(res.begin(), res.end(),<br /> ostream_iterator<string>(cout, " "));<br />cout << endl;</p><p>return 0;<br />}
當然,如果硬要顯式排序,也可以:
bool compare(string a, string b) {<br />int ax, ay;<br />int bx, by;<br />char t;</p><p>istringstream ss(a);<br />ss >> ax >> t >> ay;</p><p>ss.clear();<br />ss.str(b);<br />ss >> bx >> t >> by;</p><p>if (ax < bx<br />|| ax == bx && ay < by)<br />return true;<br />else<br />return false;<br />}</p><p>int main()<br />{<br />vector<string> vec;<br />vec.push_back("0,0");<br />vec.push_back("2,1");<br />vec.push_back("1,2");</p><p>sort(vec.begin(), vec.end(), compare);</p><p>copy(vec.begin(), vec.end(),<br />ostream_iterator<string>(cout, " "));<br />cout << endl;</p><p>return 0;<br />}<br />