Your PRogram must allow Thor to reach the light of power.
題目地址: https://www.codingame.com/ide/puzzle/power-of-thor-episode-1
通過嵌套的if條件語句來枚舉各類情況:
#include <iostream>#include <string>#include <vector>#include <algorithm>using namespace std;/** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. * --- * Hint: You can use the debug stream to print initialTX and initialTY, if Thor seems not follow your orders. **/int main(){ int lightX; // the X position of the light of power int lightY; // the Y position of the light of power int initialTX; // Thor's starting X position int initialTY; // Thor's starting Y position cin >> lightX >> lightY >> initialTX >> initialTY; cin.ignore(); int currentX = initialTX; int currentY = initialTY; // game loop while (1) { int remainingTurns; // The remaining amount of turns Thor can move. Do not remove this line. cin >> remainingTurns; cin.ignore(); // Write an action using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; // if both offset, then move in diaganol line if (currentX - lightX > 0) { if (currentY - lightY > 0){ cout << "NW" << endl; currentX--; currentY--; } else if (currentY - lightY <0){ cout << "SW" << endl; currentX--; currentY++; cerr << currentX << endl; }else { cerr << "now Y same" <<endl; cout << "W" <<endl; currentX--; } } else if (currentX - lightX < 0) { if (currentY - lightY > 0){ cout << "NE" << endl; currentX++; currentY--; } else if (currentY - lightY <0){ cout << "SE" << endl; currentX++; currentY++; }else { cout << "E" <<endl; currentX++; } } else { cerr << "now X same" <<endl; if (currentY - lightY > 0){ cout << "N" << endl; currentY--; } else if (currentY - lightY < 0){ cout << "S" << endl; currentY++; }else { // in position cerr << "now Y same" <<endl; } } // A single line providing the move to be made: N NE E SE S SW W or NW // cout << "SE" << endl; }}在物理學中可以對速度向量進行向量分解,最常用的是分解為X、Y方向兩個速度分量。
在C++實現中,雖然我們不能簡單引入速度這個概念,但是通過緩沖區的暫存,可以讓我們通過單獨判定X、Y方向的關系,分別向緩沖區中寫入內容,最后用endl一并輸出。
潛在問題是如果向緩沖區中寫出過多字符,可能因為緩沖區已滿而自動輸出了。應該可以通過臨時變量來解決。
當輸出結果與判定條件都可以進行某種對應形式的分解時,可以適當利用緩沖區(輸出緩沖區,或者臨時變量)達到分解的目的,從而簡化程序邏輯并提高效率。
CodingGame ,ower of Thor - Episode 1,C++最高票答案,2017.02.07
新聞熱點
疑難解答