1 喊山,是人双手围在嘴边成喇叭状,对着远方高山发出“喂—喂喂—喂喂喂……”的呼唤。呼唤声通过空气的传递,回荡于深谷之间,传送到人们耳中,发出约定俗成的“讯号”,达到声讯传递交流的目的。原来它是彝族先民用来求援呼救的“讯号”,慢慢地人们在生活实践中发现了它的实用价值,便把它作为一种交流工具世代传袭使用。(图文摘自:http://news.xrxxw.com/newsshow-8018.html)
2
3
4
5 一个山头呼喊的声音可以被临近的山头同时听到。题目假设每个山头最多有两个能听到它的临近山头。给定任意一个发出原始信号的山头,本题请你找出这个信号最远能传达到的地方。
6
7 输入格式:
8 输入第一行给出3个正整数n、m和k,其中n(≤10000)是总的山头数(于是假设每个山头从1到n编号)。接下来的m行,每行给出2个不超过n的正整数,数字间用空格分开,分别代表可以听到彼此的两个山头的编号。这里保证每一对山头只被输入一次,不会有重复的关系输入。最后一行给出k(≤10)个不超过n的正整数,数字间用空格分开,代表需要查询的山头的编号。
9
10 输出格式:
11 依次对于输入中的每个被查询的山头,在一行中输出其发出的呼喊能够连锁传达到的最远的那个山头。注意:被输出的首先必须是被查询的个山头能连锁传到的。若这样的山头不只一个,则输出编号最小的那个。若此山头的呼喊无法传到任何其他山头,则输出0。
12
13 输入样例:
14 7 5 4
15 1 2
16 2 3
17 3 1
18 4 5
19 5 6
20 1 4 5 7
21 输出样例:
22 2
23 6
24 4
25 0
1 #include <iostream>
2 #include <cstdio>
3 #include <cstdlib>
4 #include <cstring>
5 #include <iostream>
6 #include <algorithm>
7 #include <cmath>
8 #include <queue>
9 using namespace std;
10 #define pi acos(-1.0)
11 typedef long long ll;
12 const int N =1e4+100;
13 int n,m,k;
14 int head[N],lev[N];
15 bool vis[N];
16 struct Edge{
17 int fr,to,nex;
18 }e[N*4];
19 int a,b;
20 int cnt;
21 void add(int a,int b){
22 e[cnt].fr=a;
23 e[cnt].to=b;
24 e[cnt].nex=head[a];
25 head[a]=cnt++;
26 }
27 int bfs(int rt){
28 queue<int>Q;
29 Q.push(rt);
30 int ans=rt,maxx=0;
31 while(!Q.empty()){
32 int u=Q.front();
33 Q.pop();
34 if(lev[u]>maxx){
35 maxx=lev[u];
36 ans=u;
37 }
38 else if(lev[u]==maxx){//不能用if ,因为上一个if会让lev[u]=maxx ,那么这个if 一定会执行的
39 ans=min(ans,u);
40 }
41 for(int i=head[u];i!=-1;i=e[i].nex){
42 if(!vis[e[i].to]){
43 vis[e[i].to]=1;
44 lev[e[i].to]=lev[e[i].fr]+1;
45 Q.push(e[i].to);
46 }
47 }
48 }
49 if(ans==rt) ans=0;
50 return ans;
51 }
52 int main()
53 {
54 scanf("%d%d%d",&n,&m,&k);
55 memset(head,-1,sizeof(head));
56 cnt=0;
57 for(int i =0;i<m;i++){
58 scanf("%d%d",&a,&b);
59 add(a,b);
60 add(b,a);
61 }
62 int x;
63 while(k--){
64 //每次都要重新来找
65 memset(vis,0,sizeof(vis));
66 memset(lev,0,sizeof(lev));
67 scanf("%d",&x);
68 vis[x]=1;//不能在找到自己
69 int rt=bfs(x);
70 printf("%d\n",rt);
71 }
72 return 0;
73 }