dotcpp0740312


私信TA

用户名:dotcpp0740312

访问量:569

签 名:

等  级
排  名 4492
经  验 1624
参赛次数 0
文章发表 18
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

解题思路:
传递糖果的方式是广搜,

先定义一个node结构体

struct node
{
    int num;//节点编号
    int step;//访问步数
};

然后直接上广搜模板

void bfs()
{
    node tmp;
    tmp.num = start;
    tmp.step = 1;
    q.push(tmp);//q是node类型的队列
    now++;//now是已经访问的节点数
    while(!q.empty())
    {
        int v = q.front().num;
        int step0 = q.front().step;
        for(int i = 0; i < g[v].size(); i++)
        {
            if(now == n+1)//n是总节点数
            {
                cout << q.back().step+eat << endl;
                return;
            }
            if(vis[g[v][i]]) continue;
            tmp.num = g[v][i];
            tmp.step = step0+1;
            q.push(tmp);
            vis[tmp.num] = true;//标记已经给过糖果
            now++;
        }
        q.pop();//队首出队
     }
}

再加一个输入程序

void read()
{
    memset(vis,false,sizeof(vis));
    cin >> n >> m >> start >> eat;
    now = 0;
    int x,y;
    for(int i = 1; i > x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}


注意事项:
从1开始计数
完整代码:

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int num;
    int step;
};
int n,m,start,eat,now;
vector g[1001];//定义邻接表
queue q;//广搜的队列
bool vis[10005];//是否访问过
void read()
{
    memset(vis,false,sizeof(vis));
    cin >> n >> m >> start >> eat;
    now = 0;
    int x,y;
    for(int i = 1; i > x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}
void bfs()
{
    node tmp;
    tmp.num = start;
    tmp.step = 1;
    q.push(tmp);
    now++;
    while(!q.empty())
    {
        int v = q.front().num;
        int step0 = q.front().step;
        for(int i = 0; i < g[v].size(); i++)
        {
            if(now == n+1)
            {
                cout << q.back().step+eat << endl;
                return;
            }
            if(vis[g[v][i]]) continue;
            tmp.num = g[v][i];
            tmp.step = step0+1;
            q.push(tmp);
            vis[tmp.num] = true;
            now++;
        }
        q.pop();
    }
}
int main()
{
    read();//输入
    bfs();//广搜
    return 0;
}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区