描述
在一个吝啬的国度里有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
分析:入门的深搜题,二维数组存储不了,可以用邻接表存储,之后用vector写了一下,加深深搜的印象
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cstdio>
#include<vector>
#include<string.h>
using namespace std;
vector <int>a[100005];
int b[100005],vis[100005];
void dfs(int city)
{
vis[city]=1;
for(int i=0;i<a[city].size();i++)
{
if(!vis[a[city][i]])
{
b[a[city][i]]=city;
dfs(a[city][i]);
}
}
}
int main()
{
int t,city,n,from,to;
scanf("%d",&t);
while(t--)
{
memset(b,0,sizeof(b));
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&city);
for(int j=1;j<=n;j++)
{
a[j].clear();
}
for(int i=1;i<n;i++)
{
scanf("%d%d",&from,&to);
a[from].push_back(to);
a[to].push_back(from);
}
// for(int j=1;j<=n;j++)
// {
// while(!a[j].empty())
// {
// printf("%d ",a[j].back());
// a[j].pop_back();
// }
// printf("\n");
// }
b[city]=-1;
dfs(city);
for(int i=1;i<=n;i++)
{
printf("%d ",b[i]);
}
printf("\n");
}
return 0;
}
邻接表方法:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int vertex; //顶点数据信息
struct node *nextnode;//指向下一顶点的指标
};
typedef struct node *graph;
struct node head[1000000]; //图形顶点数组
int visited[1000000];
int ans[1000000];
void create(int num)
{
graph newnode;
graph ptr;
int from,to,temp;
for(int i=0;i<num-1;i++)
{
scanf("%d %d",&from,&to);
//建立新顶点
newnode=( graph )malloc(sizeof(struct node));
newnode->vertex=to;
newnode->nextnode=NULL;
ptr=&(head[from]);
while(ptr->nextnode!=NULL)
ptr=ptr->nextnode;
ptr->nextnode=newnode;
newnode=( graph )malloc(sizeof(struct node));
newnode->vertex=from;
newnode->nextnode=NULL;
ptr=&(head[to]);
while(ptr->nextnode!=NULL)
{
ptr=ptr->nextnode;
}
ptr->nextnode=newnode;
}
}
//深度搜索
void dfs(int current)
{
graph ptr,pre;
visited[current]=1;
pre=&(head[current]);
ptr=head[current].nextnode;
while(ptr!=NULL)
{
if(visited[ptr->vertex]==0)
{
ans[ptr->vertex]=current;
dfs(ptr->vertex);
}
ptr=ptr->nextnode;
}
}
int main()
{
int n,c_now,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&c_now);
for(int i=1;i<=n;i++)
{
head[i].vertex=i;
head[i].nextnode=NULL;
visited[i]=0;
}
create(n);
// for(int i=1;i<=n;i++)
// {
// graph p;
// p=&(head[i]);
// while(p->nextnode!=NULL)
// {
// printf("%d->",p->vertex);
// p=p->nextnode;
// }
// printf("%d\n",p->vertex);
// }
dfs(c_now);
ans[c_now]=-1;
printf("%d",ans[1]);
for(int i=2;i<=n;i++)
{
printf(" %d",ans[i]);
}
printf("\n");
}
return 0;
}
希望自己坚持,把图的存储都学习完!