D. Dice Game(bfs或者找规律)

这道题目要求在每次转动90度时骰子朝上的数字总和必须达到给定的n。初始值为0,初始数字1不计入总和。需要找到达到n的最小转动次数,若无法达成则输出-1。输入包含测试用例数量T和每个用例的目标和n(1≤T≤200, 1≤n≤10^4)。" 113231150,10542423,使用ZeroMQ实现MySQL数据库与进程通信,"['数据库进程间通信', '数据库插件', '消息队列', 'ZeroMQ', 'MySQL']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题源
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值