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

//有点郁闷深搜过来, 广搜没过,求大神指点啊
#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值