cin>>t;
while (t--)
{
cin>>n;
cin>>m;
if (n==m)
cout<<"0\n";
else
{
//Breadth First Search Tree:
queue <gnode*> gqueue;
bft_data bft=bft_data();
list<gnode>* gp;
list<gnode>::iterator it;
gp=_gfind(graph,n);// finds list containing gnode with n value
gnode* st=gfind(gp,n),*tmp,*_st;//finds gnode with n value
_st=st;
bft.w[st->v]=0;
bft.pn[st->v]=NULL;
bft.c[st->v]=1;
gqueue.push(st);
while (!gqueue.empty())
{
st=gqueue.front();
gqueue.pop();
gp=_gfind(graph,st->v);
it=(*gp).begin();
for (++it;it!=(*gp).end();it++)//initialized with ++it to skip fist element of list
{
tmp=&(*it);
// cout<<tmp->v<<"\n";
// getchar();
if (bft.c[tmp->v]==0)
{
bft.pn[tmp->v]=st;
bft.c[tmp->v]=1;
bft.w[tmp->v]=bft.w[st->v]+1;
gqueue.push(tmp);
}
}
}
if(bft.w[m]!=SIZE)
cout<<bft.w[m]<<"\n";
else
cout<<"Impossible\n";
bft.~bft_data();
}
}
此代码片段通过构造 bfs 树来计算具有值 n 和 m 的节点的 b/w 距离。但是在外部 while 循环的第一次迭代中构造的 bft 树以某种方式保留了它的值,while 循环的进一步迭代对 bft 没有影响
这里的图表是类型vector<list<gnode>>
bfs 是 bft_data 类的对象:
class bft_data
{
public:
int w[SIZE],c[SIZE];
gnode* pn[SIZE];
bft_data()
{
memset(w,SIZE,SIZE);
memset(c,0,SIZE);
memset(pn,NULL,SIZE);
}
};