喊山,一个山头呼喊的声音可以被临近的山头同时听到。题目假设每个山头最多有两个能听到它的临近山头。给定任意一个发出原始信号的山头,本题请你找出这个信号最远能传达到的地方。
输入格式:
输入第一行给出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
解题思路
- 正常BFS即可,但是注意到里面其实有一个比较成分,无论怎么设计顺序也没法讨巧减少时间,索性就不剪枝了,同一层的节点都进入队列,比较就行了
- 现在才发现邻接表是真的快,像这道题就是,用其他的数据结构会超时
代码
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <cstdio>
#include <bitset>
using namespace std;
const int N = 10000 + 3;
static int n, m, k;
static vector<int> v1[N];
int query(int index){
int curr, clevel;
int result = N, rlevel = -1;
queue<int> q1, qlevel;
bitset<N> isUsed;
isUsed.reset();
q1.push(index);
qlevel.push(0);
while(!q1.empty()){
curr = q1.front(), clevel = qlevel.front();
// cout << curr << " " << clevel << endl;
q1.pop(); qlevel.pop();
if(isUsed[curr]) continue;
else isUsed[curr] = 1;
if(clevel > rlevel || (clevel == rlevel && result > curr)){
result = curr;
rlevel = clevel;
}
for(int i=0; i<v1[curr].size(); i++){
if(!isUsed[v1[curr][i]]){
q1.push(v1[curr][i]);
qlevel.push(clevel + 1);
}
}
}
return result;
}
int main(){
cin >> n >> m >> k;
for(int i=0; i<m; i++){
int i1, i2;
cin >> i1 >> i2;
v1[i1].push_back(i2);
v1[i2].push_back(i1);
}
for(int i=0; i<k; i++){
// cout << "i = " << i << endl;
int index; cin >> index;
if(query(index) != index) cout << query(index) << endl;
else cout << "0" << endl;
}
return 0;
}