原题链接:分糖果
解题思路:
传递糖果的方式是广搜,
先定义一个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 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复