您的位置:首页 > 其它

NYOJ 20 吝啬的国度无向图的遍历

2012-05-15 22:21 417 查看
View Code

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<malloc.h>
#include<cstring>
#define N 100001

using namespace std;

typedef struct city
{
int v;
struct city *next;
}City;

City c
;
int n,visit
;
int father
;

void connect(int from,int to)//连接两个点
{
City *p;
p = (City *)malloc(sizeof(City));
p->v = to;
p->next = c[from].next;
c[from].next = p;
}

void destory(City *p)//递归释放空间(从阿焦那里学的,嘻嘻~)
{
if(p == NULL)
return;
destory(p->next);
}

queue<City>q;
int main()
{
int i,j,ncases,S;
int a,b;
City *link;

scanf("%d",&ncases);
while( ncases-- )
{
scanf("%d%d",&n,&S);
memset(visit,0,sizeof(visit));
for(i=1; i<=n; i++)
{
c[i].v = i;
c[i].next = NULL;
}
for(i=1; i<n; i++)
{
scanf("%d%d",&a,&b);
connect(a,b);
connect(b,a);
}
visit[S] = 1;
father[S] = -1;
q.push(c[S]);
while( !q.empty() )
{
City p = q.front();
q.pop();
link = p.next;
while( link != NULL)
{
if( !visit[link->v] )
{
father[link->v] = p.v;
visit[link->v] = 1;
q.push(c[link->v]);
}
link = link->next;
}
}
while( !q.empty())
q.pop();
printf("%d",father[1]);
for(i=2; i<=n; i++)
{
printf(" %d",father[i]);
}
printf("\n");
for(i=1; i<=n; i++)
destory(&c[i]);
}
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: