题解:UVA10409 Die Game
好不容易找到一个可以写题解的题(开心)
题目传送门。
题目分析
模拟一个骰子的旋转过程,其骰子的初始状态是:顶部为 north、south、east、west),根据旋转方向更新骰子的状态,并输出旋转后顶部的数字。
解题思路
-
用六个变量来表示骰子的六个面:
top、bottom、north、south、west、east,分别表示顶、底、北、南、西、东面。 -
初始状态:
top = 1,north = 2,west = 3,bottom = 6,south = 5,east = 4 -
根据旋转方向更新骰子的各个面。
-
Code
#include <iostream>
#include <string>
using namespace std;
int main() {
int T;
while (cin >> T && T != 0) { // 读取T,当T为0时结束
int top = 1, bottom = 6, north = 2, south = 5, west = 3, east = 4; // 初始化骰子的状态
for (int i = 0; i < T; ++i) {
string direction;
cin >> direction; // 读取旋转方向
// 根据旋转方向更新骰子的状态
if (direction == "north") {
int temp = top;
top = south;
south = bottom;
bottom = north;
north = temp;
} else if (direction == "south") {
int temp = top;
top = north;
north = bottom;
bottom = south;
south = temp;
} else if (direction == "east") {
int temp = top;
top = west;
west = bottom;
bottom = east;
east = temp;
} else if (direction == "west") {
int temp = top;
top = east;
east = bottom;
bottom = west;
west = temp;
}
}
cout << top << endl; // 输出旋转后的顶部数字
}
return 0;
}
- 每次旋转操作的时间复杂度为
O (1) ,总共有T 次操作,因此总时间复杂度为O(T) 。