您的位置:首页 > 其它

南阳理工 oj 图的邻接表dfs dfs 均可

2013-06-04 11:55 218 查看
//有点郁闷深搜过来, 广搜没过,求大神指点啊
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int n;
struct node
{
int num;
struct node * next;
};
struct data
{
int prior;
node * last_linked;
}map[100000];

node q[20000];
int front, rear;
void del(  )
{
int i;
node *p, *q;
for (i = 1; i <= n; i++)
{
p = map[i].last_linked;
while (p != NULL)
{
q = p->next;
delete p;
p = q;
}
}
};

void dfs( int current, int prior )
{
map[current].prior = prior;
node * p = map[current].last_linked;
while( p != NULL )
{
if( map[p->num].prior == 0 )
{
dfs( p->num, current );
}
p = p->next;
}
};
void bfs( int current, int prior )
{
node last;
front = rear = 0;
map[current].prior = prior;
node * p;
node temp;
temp.num = current;
temp.next = NULL;
q[rear++] = temp;
while( front < rear )
{
last = q[front++];
p = map[last.num].last_linked;
while( p != NULL )
{
if( map[p->num].prior == 0 )
{
map[p->num].prior = last.num;
q[rear++] = *p;
}
p = p->next;
}
}
}
int main()
{
freopen( "1.txt", "r", stdin );
node *p;
int T, start, u, v;
scanf( "%d\n", &T );
while( T-- )
{
scanf( "%d%d", &n, &start );
for( int i = 1; i <= n; i++  )
{
map[i].prior = 0;
map[i].last_linked = NULL;
}
for( int i = 1; i < n; i++ )
{
scanf( "%d%d", &u, &v );
p = new node;
p->num = v;
p->next = map[u].last_linked;
map[u].last_linked = p;
p = new node;
p->num = u;
p->next = map[v].last_linked;
map[v].last_linked = p;
}
bfs( start, -1 );
//dfs(start, -1 );
int i;
for ( i = 1; i < n; i++)
{
printf("%d ", map[i].prior );
}
printf("%d\n", map[i].prior );
del( );
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: