您的位置:首页 > 其它

NYOJ 20 吝啬的国度

2013-11-09 22:28 211 查看
吝啬的国度

时间限制:1000 ms | 内存限制:65535 KB

难度:3

描述

在一个吝啬的国度里有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>
#define MAX 100005

typedef struct node
{
int c;
struct node *next;
};

void dfs(node *city, int num)
{
node *t;
for(t=city[num].next; t!=NULL; t=t->next)
{
if(city[t->c].c==0)
{
city[t->c].c=num;
dfs(city, t->c);
}
}
}

int main()
{
//    freopen("20.txt", "r", stdin);
int m,n,s,i,a,b;
node *p1, *p2;
node *city;
scanf("%d",&m);
while(m--)
{
scanf("%d %d", &n, &s);
city=(node *)malloc( (n+1)*sizeof(node) );
for(i=1; i<+n; i++)
{
city[i].c=0;
city[i].next=NULL;
}
for(i=1;i<n;i++)
{
scanf("%d %d",&a,&b);
p1=(node *)malloc(sizeof(node));
p1->c=b;
p1->next=city[a].next;
city[a].next=p1;
p2=(node *)malloc(sizeof(node));
p2->c=a;
p2->next=city[b].next;
city[b].next=p2;
}
city[s].c=-1;
dfs( city, s);
for(i=1;i<=n-1;i++)
printf("%d ", city[i].c);
printf("%d\n", city[i].c);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索 dfs malloc