nyoj 20 吝啬国度【dfs】

版权声明:本文为博主原创文章,转载请注明出处,谢谢。 https://blog.csdn.net/nailnehc/article/details/50153053


吝啬的国度
时间限制: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

刚开始做的时候,我单纯的以为可以用并查集直接怼,然而我错了【是我提交出错】,直到我看到数据结构书时,才想到用树来解决【刚学不就,用不熟,因为有指针,而我对指针有一种无法驾驭的感觉】,这道题可以用树的孩子表示法,然后用深搜就可以解决。

已Accept代码【c++提交】【不会用vector】╮(╯﹏╰)╭

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;

int n, s;

typedef struct Son{
	int data;
	struct Son *next;
}Son, *Sson;

struct Node{
	int data;
	int data2;//储存最后的序列
	struct Son *next;
}node[100001];

void init(int k) {
	for(int i = 0; i <= k; i++) {
		node[i].data = i;
		node[i].next = NULL;
		node[i].data2 = -1;
	}
}

void Get_Up(int a, int b) {
	Sson L  = (Sson)malloc(sizeof(Son));
	Sson K  = (Sson)malloc(sizeof(Son));
	L -> next = node[a].next;
	node[a].next = L;
	L -> data = b;
	K -> next = node[b].next;
	node[b].next = K;
	K -> data = a;
}

void DFS(int k) {
	Sson L = node[k].next;
	while(L) {
		if(node[L -> data].data2 == -1) {
			node[L -> data].data2 = k;
			DFS(L -> data);
			L = L -> next;
		}
		else
			L = L -> next;
	}
}

int main() {
	int t, a, b;
	scanf("%d", &t);
	while(t--) {
		scanf("%d%d", &n, &s);
		init(n);
		for(int i = 1; i < n; i++) {
			scanf("%d%d", &a, &b);
			Get_Up(a, b);
		}
		DFS(s);
		node[s].data2 = -1;
		printf("%d", node[1].data2);
		for(int i = 2; i <= n; i++)
			printf(" %d", node[i].data2);
		printf("\n");
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/nailnehc/article/details/50153053