题目:https://www.jisuanke.com/course/738/37805
bfs的步数记录代码:
int last = 1,cur = 0;
int step = 1;
while(队列不为零){
q.pop;
last--;
while(遍历点){
cur++;
}
if(last==0){
step++;
last = cur;
cur = 0;
}
}
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1005;
const int MAX_M = 10005;
int p[MAX_N<<1] = {0};
int eid,n,m,C;
int vis[MAX_N<<1] = {0};
queue<int> q;
struct E
{
int v;
int next;
}edge[MAX_M<<1];
void init()
{
memset(p,-1,sizeof(p));
eid = 0;
}
int bfs(int u,int x)
{
while(!q.empty()){
q.pop();
}
q.push(u);
if(u==x) return 0;
memset(vis,0,sizeof(vis));
int last = 1,cur = 0;
int step = 1;
while(!q.empty()){
int d = q.front();
q.pop();
last--;
for(int i=p[d];i!=-1;i=edge[i].next){
if(!vis[edge[i].v]){
if(x==edge[i].v){
return step;
}
vis[edge[i].v] = 1;
q.push(edge[i].v);
cur++;
}
}
if(last==0){
step++;
last = cur;
cur = 0;
}
}
}
void mergex(int u,int v)
{
edge[eid].v = v;
edge[eid].next = p[u];
p[u] = eid++;
}
int main()
{
cin>>n>>m>>C;
init();
while(m--){
int u,v;
cin>>u>>v;
mergex(u,v);
mergex(v,u);
}
for(int i=1;i<=n;i++){
cout<<bfs(C,i)<<'\n';
}
return 0;
}
有时间在记录多点思维上的东西。