描述
在一个吝啬的国度里有N个城市,这N个城市间只有N-1条路把这个N个城市连接起来。现在,Tom在第S号城市,他有张该国地图,他想知道如果自己要去参观第T号城市,必须经过的前一个城市是几号城市(假设你不走重复的路)。
输入
第一行输入一个整数M表示测试数据共有M(1<=M<=5)组
每组测试数据的第一行输入一个正整数N(1<=N<=100000)和一个正整数S(1<=S<=100000),N表示城市的总个数,S表示参观者所在城市的编号
随后的N-1行,每行有两个正整数a,b(1<=a,b<=N),表示第a号城市和第b号城市之间有一条路连通。
输出
每组测试数据输N个正整数,其中,第i个数表示从S走到i号城市,必须要经过的上一个城市的编号。(其中i=S时,请输出-1)
样例输入
1
10 1
1 9
1 8
8 10
10 3
8 6
1 2
10 4
9 5
3 7
样例输出
-1 1 10 10 9 8 3 1 1 8
#include<stdio.h>
#include<malloc.h>
struct Node
{
int i;
struct Node* p;
};
struct head
{
int f;
int flag;
struct Node* p;
};
void init(int* a)
{
a[0]=1;
a[1]=2;
}
void push(int* a,int s)
{
a[a[1]]=s;
a[1]++;
}
int pop(int* a)
{
if(a[0]==a[1]-1)
return -1;
a[0]++;
return a[a[0]];
}
int main()
{
int m,n,s,k=0;
int c,d;
int *a=0;
struct head* h=0;
struct Node* q=0;
scanf("%d",&m);
while(m--)
{
scanf("%d %d",&n,&s);
h=(struct head*)malloc(sizeof(struct head)*(n+1));
a=(int*)malloc(sizeof(int)*(2*n+1));
for(int j=1;j<=n;j++)
{
h[j].flag=0;
h[j].f=0;
h[j].p=NULL;
}
for(int j=1;j<=n-1;j++)
{
scanf("%d %d",&c,&d);
q=(struct Node*)malloc(sizeof(struct Node)*1);
q->i=d;
q->p=h[c].p;
h[c].p=q;
q=(struct Node*)malloc(sizeof(struct Node)*1);
q->i=c;
q->p=h[d].p;
h[d].p=q;
}
h[s].f=-1;
init(a);
push(a,s);
k=pop(a);
while(k!=-1)
{
if(h[k].flag!=0)
{
k=pop(a);
continue;
}
h[k].flag=1;
q=h[k].p;
while(q!=NULL)
{
push(a,q->i);
if(h[q->i].f==0)
{
h[q->i].f=k;
}
q=q->p;
}
k=pop(a);
}
for(int j=1;j<=n;j++)
{
printf("%d ",h[j].f);
}
printf("\n");
}
return 0;
}