吝啬的国度
时间限制:
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
-
第一行输入一个整数M表示测试数据共有M(1<=M<=5)组
初学广搜,当时数据结构没学,感谢乾神帮忙/(ㄒoㄒ)/~~。自己摸索着建图,用c写的,后来学会更多知识后知道用c++STL写更为方便,纯手工模拟队列操作,链表操作,崩溃多次,最终还是过了,这其实就是最基本的广搜题,用c++的STL和邻接矩阵建图能节省一大部分的代码量,送给初学者们看看吧。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct city{
int d;
int parent;
int flag;
struct city *next;
};
typedef struct city path;
path *queue[100000];
int result[100000];
void bfs(path *s,path num[],int count){
int front=0,last=0;
queue[front]=s;
result[queue[front]->d]=-1;
while(last>=front){
path *tmp;
num[queue[front]->d].flag=0;
tmp=(num+queue[front]->d)->next;
while(tmp){
if(tmp->flag&&!result[tmp->d]){
queue[++last]=tmp;
tmp->flag=0;
result[tmp->d]=queue[front]->d;
}
tmp=tmp->next;
}
front++;
}
for(int j=1;j<=count;j++)
printf("%d ",result[j]);
return;
}
int main()
{
int t;
scanf("%d",&t);
for(int i=0;i<t;i++){
int n,X;
scanf("%d%d",&n,&X);
if(n==1){
printf("-1\n");
continue;
}
path num[n];
for(int j=1;j<=n;j++){
num[j].d=j;
num[j].flag=1;
num[j].parent=-1;
num[j].next=NULL;}
for(int j=0;j<n-1;j++){
int x,y;
scanf("%d%d",&x,&y);
path *p,*q=num+x,*m=num+y,*v;
p=(path*)malloc(sizeof(path));
v=(path*)malloc(sizeof(path));
p->next=NULL;
p->flag=1;
p->d=y;
v->next=NULL;
v->flag=1;
v->d=x;
while(q->next)q=q->next;
q->next=p;
while(m->next)m=m->next;
m->next=v;
}
bfs(num+X,num,n);
putchar('\n');
for(int j=0;j<100000;j++)
queue[j]=NULL;
for(int j=0;j<100000;j++)
result[j]=0;
}
return 0;
}
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
using namespace std;
int v[100004],s,n;
map<int,vector<int> >q;
struct node{
int x,y;
};
void bfs(){
int ans[100004];
ans[s] = -1;
node t;
t.x = s,t.y = -1;
v[s] = 1;
queue<node>p;
p.push(t);
while(!p.empty()){
t = p.front();
p.pop();
ans[t.x] = t.y;
for(int i = 0;i < q[t.x].size();i++){
if(!v[q[t.x][i]]){
node temp;
temp.x = q[t.x][i];
temp.y = t.x;
p.push(temp);
v[q[t.x][i]] = 1;
}
}
}
for(int i = 1;i <= n;i++)
printf("%d ",ans[i]);
return;
}
int main()
{
int m,a,b;
cin>>m;
while(m--){
scanf("%d%d",&n,&s);
memset(v,0,sizeof(v));
q.clear();
for(int i = 0;i < n-1;i++){
scanf("%d%d",&a,&b);
q[a].push_back(b);
q[b].push_back(a);
}
bfs();
}
return 0;
}