1.邻接表建无向图(深度搜索)
邻接表避免了(邻接矩阵)没必要的空间浪费!!!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int visit[100005];int map[100005];
typedef struct node{
int num;
struct node*next;
}VexNode;
struct Vex{
VexNode*next;
};
Vex vex[100005];
void depth(int n)
{
visit[n]=1;
VexNode *p;p=(VexNode*)malloc(sizeof(VexNode));
p=vex[n].next;
while(p!=NULL){
if(!visit[p->num]){
map[p->num]=n;
depth(p->num);
}
p=p->next;
}
}
int main()
{
int T,N,s,a,b,i;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&N,&s);
memset(map,0,sizeof(int)*(N+1));
memset(visit,0,sizeof(visit));
for(i=1;i<=N;i++){
vex[i].next=NULL;
}
for(i=1;i<N;i++)
{
scanf("%d%d",&a,&b);
VexNode *p;
p=(VexNode*)malloc(sizeof(VexNode));
p->num=b;
p->next=vex[a].next;
vex[a].next=p;
VexNode *p1;
p1=(VexNode*)malloc(sizeof(VexNode));
p1->num=a;
p1->next=vex[b].next;
vex[b].next=p1;
}
depth(s);
map[s]=-1;
for(i=1;i<N;i++)
printf("%d ",map[i]);
printf("%d\n",map[N]);
}
return 0;
}
2.看别人的巧妙算法
基于”吝啬”:N个城市用N-1条路连接起来,输入a,b;map[b]=a:b的上一个城市是a,如果b出现过就map[a]=b(但同时注意如果a如果也出现过得情况!),就是adjust函数:递归调整下去(直到没出现的元素)!
#include<stdio.h>
#include<string.h>
int map[100001];int s;
void adjust(int n)
{
int pri=map[n];
if(pri!=0||pri==s){
adjust(pri);
map[pri]=n;
}
}
int main()
{
int T,N,a,b,i;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&N,&s);memset(map,0,sizeof(int)*(N+1));
for(i=1;i<N;i++){
scanf("%d%d",&a,&b);
if(map[b]==0&&b!=s)
map[b]=a;
else{
adjust(a);
map[a]=b;
}
}
adjust(s);
map[s]=-1;
for(i=1;i<N;i++)
printf("%d ",map[i]);
printf("%d\n",map[N]);
}
return 0;