4

2022寒假精进训练-7

 2 years ago
source link: https://hbuacm.github.io/2022/02/09/%E3%80%902022%E5%AF%92%E5%81%87%E7%B2%BE%E8%BF%9B%E8%AE%AD%E7%BB%83-7%E3%80%917-11%20%E6%B7%B1%E5%85%A5%E8%99%8E%E7%A9%B4/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

HBUACM

【2022寒假精进训练-7】7-11 深入虎穴
发表于 2022-02-09| 更新于 2022-02-15|2022寒假精进程序设计训练2022寒假精进训练-7
阅读量:16

著名的王牌间谍 007 需要执行一次任务,获取敌方的机密情报。已知情报藏在一个地下迷宫里,迷宫只有一个入口,里面有很多条通路,每条路通向一扇门。每一扇门背后或者是一个房间,或者又有很多条路,同样是每条路通向一扇门…… 他的手里有一张表格,是其他间谍帮他收集到的情报,他们记下了每扇门的编号,以及这扇门背后的每一条通路所到达的门的编号。007 发现不存在两条路通向同一扇门。

内线告诉他,情报就藏在迷宫的最深处。但是这个迷宫太大了,他需要你的帮助 —— 请编程帮他找出距离入口最远的那扇门。

输入格式:

输入首先在一行中给出正整数 N(<105),是门的数量。最后 N 行,第 i 行(1≤i≤N)按以下格式描述编号为 i 的那扇门背后能通向的门:

K D[1] D[2] ... D[K]

其中 K 是通道的数量,其后是每扇门的编号。

输出格式:

在一行中输出距离入口最远的那扇门的编号。题目保证这样的结果是唯一的。

输入样例:

输出样例:

求树中距离根节点最远的节点。使用广度优先算法,mp存放可以互通的门编号,注意门的互通是双向的;根节点题目中未给出,因为根节点不是任何节点的子节点,所以在输入的时候记录一下子节点编号,最后未出现的结点即为根节点。然后进行BFS遍历即可,因为题目保证结果唯一,所以最后的结点极为最远的结点。

这道题跟7-15 喊山那道题目做法思路相同

#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector<int> mp[100005];
int vis[100005], ans;
void bfs(int u) {
queue<int> q;
q.push(u);
vis[u] = 1;
while(!q.empty()) {
int f = q.front();
ans = f;
q.pop();
for(int i = 0; i < mp[f].size(); i++) {
int v = mp[f][i];
if(vis[v]) continue;
vis[v] = 1;
q.push(v);
}
}
}
int main() {
int n;
cin >> n;
for(int i = 1; i <= n; i++) {
int k;
cin >> k;
while(k--) {
int t;
cin >> t;
vis[t] = 1;
mp[i].push_back(t);
mp[t].push_back(i);
}
}
int s;
for(int i = 1; i <= n; i++) {
if(vis[i] == 0) {
s = i;
break;
}
}
memset(vis, 0, sizeof(vis));
bfs(s);
cout << ans;
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK