题源
http://codeforces.com/gym/101502/problem/D
说一下题的意思,给你个数字n,每次你转动90度必须改变骰子朝上的数字,让朝上的数字相加,得到n。你得转动多少次?初始时数字1朝上,但这个1不算总数里,也就是你的初始值是0,不是1。
Input
The first line contains an integer T (1 ≤ T ≤ 200), where T is the number of test cases.
Then T lines follow, each line contains an integer n (1 ≤ n ≤ 10^4), where n is the required sum you need to reach.
Output
For each test case, print a single line containing the minimum number of required moves to reach the given sum. If there is no answer, print -1.
Example
Input
2
5
10
Output
1
2
先找一下每个朝上的数字转一下能转到什么数字。自己把筛子画出来就行了。
我在代码里解释每步什么意思。
#include <bits/stdc++.h>
using namespace std;
int vis[11111], n;
struct node
{
int num, sum, step; node里存的分别为当前朝上的数字时多少,
}; 当前累加的数多少,转了几次了。
int d[7][4] = //这个数组是每个数字朝上时能转到的数字。
{
0, 0, 0, 0,
2, 3, 4, 5,
1, 3, 4, 6,
1, 2, 5, 6,
1, 2, 5, 6,
1, 3, 4, 6,
2, 3, 4, 5
};
void bfs(int x);
int main()
{
string s;
int t;
cin >> t;
while(t--)
{
memset(vis, 0, sizeof(vis));
cin >> n;
bfs(0);
}
return 0;
}
void bfs(int x)
{
vis[x] = 1;
queue<node> q;
q.push((node)
{
1,0,0 初始是1朝上,总和为0,转了0次。
});
while(q.size())
{
node now = q.front();
q.pop();
if(now.sum == n)
{
cout << now.step << endl; 如果加到了n,输出步数结束就行了。
return;
}
for(int i = 0; i < 4; i++)
{
int tot = now.sum+d[now.num][i]; 遍历此点能转到的4个数字。
if(vis[tot] == 0 && tot < n) 这个 tot < n 很重要,如果tot>n说明累加超过n了,
{ 不管再怎么加都不会是n,就不用管这种情况。
q.push((node)
{
d[now.num][i], tot, now.step+1
});
vis[tot] = 1; 累加到tot的情况已经被遍历到了。
}
}
}
cout << "-1" << endl;
return;
}