喊山,是人双手围在嘴边成喇叭状,对着远方高山发出“喂—喂喂—喂喂喂……”的呼唤。呼唤声通过空气的传递,回荡于深谷之间,传送到人们耳中,发出约定俗成的“讯号”,达到声讯传递交流的目的。原来它是彝族先民用来求援呼救的“讯号”,慢慢地人们在生活实践中发现了它的实用价值,便把它作为一种交流工具世代传袭使用。
一个山头呼喊的声音可以被临近的山头同时听到。题目假设每个山头最多有两个能听到它的临近山头。给定任意一个发出原始信号的山头,本题请你找出这个信号最远能传达到的地方。
输入格式:
输入第一行给出3个正整数n
、m
和k
,其中n
(≤10000)是总的山头数(于是假设每个山头从1到n
编号)。接下来的m
行,每行给出2个不超过n
的正整数,数字间用空格分开,分别代表可以听到彼此的两个山头的编号。这里保证每一对山头只被输入一次,不会有重复的关系输入。最后一行给出k
(≤10)个不超过n
的正整数,数字间用空格分开,代表需要查询的山头的编号。
输出格式:
依次对于输入中的每个被查询的山头,在一行中输出其发出的呼喊能够连锁传达到的最远的那个山头。注意:被输出的首先必须是被查询的个山头能连锁传到的。若这样的山头不只一个,则输出编号最小的那个。若此山头的呼喊无法传到任何其他山头,则输出0。
输入样例:
7 5 4
1 2
2 3
3 1
4 5
5 6
1 4 5 7
输出样例:
2
6
4
0
算法思路:这其实是一个无向图的深度遍历。但是总给我一种双向链表的感觉,所以强行用了双向链表。效率没深度遍历高,但也是一种方法,分享下。(注意双项链表构建后还要进行一定的处理)
#include<stdio.h>
#include<algorithm>
using namespace std;
struct mountain {
int left = 0;
int right = 0;
}mount[10001];
bool vis[10001];
void printAnswer(int x) {
if (!mount[x].left && !mount[x].right) { printf("0\n"); return; }
int lenleft = 0;
int lenright = 0;
int l = x;
while (mount[l].left) {
if (mount[l].left == x) {
int temp = lenleft / 2;
while (temp--) {
l = mount[l].right;
}
if (!(lenleft & 1))
l = l < mount[l].left ? l : mount[l].left;
printf("%d\n", l);
return;
}
l = mount[l].left;
lenleft++;
}
int r = x;
while (mount[r].right) {
r = mount[r].right;
lenright++;
}
if (lenleft > lenright) printf("%d\n", l);
else if (lenleft == lenright) {
if (l < r) printf("%d\n", l);
else printf("%d\n", r);
}
else printf("%d\n", r);
}
int main() {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
int i;
int x, y;
for (i = 0; i < m; i++) {
scanf("%d%d", &x, &y);
if (mount[x].right)
{
mount[x].left = y;
if (mount[y].right)
mount[y].left = x;
else mount[y].right = x;
}
else {
mount[x].right = y;
if (mount[y].left)
mount[y].right = x;
else mount[y].left = x;
}
}
for (i = 1; i <= n; i++) {
vis[i] = false;
}
for (i = 1; i <= n; i++) {
if (vis[i]) continue;
int pre;
int u = i;
while (u&&!vis[u]) {
vis[u] = true;
pre = u;
u = mount[pre].right;
if (mount[u].left == pre) continue;
else {
swap(mount[u].left, mount[u].right);
u = mount[pre].right;
}
}
}
for (i = 0; i < k; i++) {
scanf("%d", &x);
printAnswer(x);
}
return 0;
}