今天一搞AC的哥们问了这一题,,它是用邻接表写的,,而且还是用动态的,,让我给他找错,我深知我没写过的,它硬是让我给他找,这不是坑爹嘛,最后实在木办法,,我给他写了个静态的邻接表,它却很淡定的说我要的是动态的,,很是无语啊,,
这一题就是bfs,以前是用stl写了,今天自己写了一下,,,感觉还行,,调试时wa了2次,,,真的需要有待提高的,,,
#include<iostream>
#include<string.h>
#include<cstdio>
#include<queue>
#define N 100001
using namespace std;
int a[N];
typedef struct { int to,next;
}Node;
Node node[2*N];
int num[N],tot,n,s;
void init()
{ tot=0;
memset(a,0,sizeof(a));
memset(num,-1,sizeof(num));
}
void Add(int aa,int b)
{ node[tot].to=b;
node[tot].next=num[aa];
num[aa]=tot++;
}
void bfs()
{ queue<int>Q;
Q.push(s);
while(!Q.empty())
{ int u=Q.front();
Q.pop();
for(int i=num[u];i!=-1;i=node[i].next)
{ if(a[node[i].to]==0)
{ a[node[i].to]=u;
Q.push(node[i].to);
}
}
}
}
int main()
{ int Case;
scanf("%d",&Case);
while(Case--)
{ init();
scanf("%d%d",&n,&s);
a[s]=-1;
for(int i=1;i!=n;++i)
{ int a,b;
scanf("%d%d",&a,&b);
Add(a,b);
Add(b,a);
}
bfs();
for(int i=1;i<=n;++i)
printf("%d ",a[i]);
printf("\n");
}return 0;
}