P11046 [蓝桥杯 2024 省 Java B] 星际旅行
一、题目简述
小明准备在一个有个星球的星系进行星际旅行,星系中有 道双向传送门连接不同的星球(任意两颗星球之间最多只有一个传送门)。有 个 “旅游盲盒”,每个盲盒规定了旅行的起始星球和最多可以使用传送门的次数。从起始星球 出发,使用传送门不超过规定次数能到达的所有星球都可以去旅行。要求计算在随机选择一个盲盒的情况下,能旅行到的不同星球的数量的期望。
二、解法说明
- 构建图的数据结构
- 使用邻接表来表示星系中的星球和传送门。邻接表是一种常用的数据结构,用于表示图。在这个问题中,每个星球可以看作是图中的一个节点,传送门可以看作是连接节点的边。
- 创建一个大小为的
vector<vector<int>>类型的容器graph,用于存储每个星球连接的其他星球。这样可以方便地进行深度优先搜索。 - 创建一个大小为的
vector<int>类型的容器visited,用于标记在深度优先搜索过程中每个星球是否被访问过。初始时,所有星球都未被访问,即都标记为。
- 读取输入并构建图
- 首先读取输入的星球数量、传送门数量和盲盒数量。
- 然后,对于每一道传送门,读取两个星球的编号和,并将它们互相添加到对方的邻接列表中,即
graph[a_i].push_back(b_i)和graph[b_i].push_back(a_i)。这样就构建了星系的图结构。
- 深度优先搜索 (
DFS) 或广度优先搜索 (BFS) 计算可到达星球数量DFS或BFS函数用于计算从给定星球出发,在剩余传送门使用次数内可以到达的星球数量。- 如果剩余传送门使用次数小于,则无法到达任何新的星球,返回。
- 将当前星球标记为已访问 (
visited[node] = 1) ,并初始化可到达星球数量为(当前星球本身)。 - 遍历当前星球连接的所有邻居星球,如果邻居星球未被访问,则递归调用
DFS函数计算从邻居星球出发可以到达的星球数量,并累加到当前可到达星球数量中。 - 最后返回可到达星球数量。
- 计算期望
- 对于每个盲盒方案,首先将
visited数组重置为全,表示所有星球都未被访问。 - 然后从盲盒规定的起始星球和最多使用传送门次数开始,调用
DFS函数计算可以到达的星球数量,并累加到total变量中。 - 遍历完所有盲盒方案后,将
total除以盲盒数量,得到能旅行到的不同星球的数量的期望。
- 对于每个盲盒方案,首先将
- 输出结果
- 使用
cout << fixed << setprecision(2) << expectation << endl;输出期望结果,保留两位小数。
- 使用
三、代码实现:
35分的DFS代码:
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
int n, m, Q;
vector<vector<int>> graph;
vector<int> visited;
int dfs(int node, int remainingSteps) {
if (remainingSteps < 0) {
return 0;
}
visited[node] = 1;
int count = 1;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
count += dfs(neighbor, remainingSteps - 1);
}
}
return count;
}
int main() {
cin >> n >> m >> Q;
graph.resize(n + 1);
visited.resize(n + 1, 0);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
int total = 0;
for (int i = 0; i < Q; i++) {
int x, y;
cin >> x >> y;
fill(visited.begin(), visited.end(), 0);
int count = dfs(x, y);
total += count;
}
double expectation = static_cast<double>(total) / Q;
cout << fixed << setprecision(2) << expectation << endl;
return 0;
}100分的BFS代码:
#include <iostream>
#include <vector>
#include <queue>
#include <iomanip>
using namespace std;
vector<vector<int>> adjList;
int n, m, Q;
int bfs(int start, int limit) {
vector<bool> visited(n + 1, false);
queue<pair<int, int>> q;
q.push({start, 0});
visited[start] = true;
int count = 1;
while (!q.empty()) {
int curr = q.front().first;
int steps = q.front().second;
q.pop();
for (int neighbor : adjList[curr]) {
if (!visited[neighbor] && steps + 1 <= limit) {
q.push({neighbor, steps + 1});
visited[neighbor] = true;
count++;
}
}
}
return count;
}
int main() {
cin >> n >> m >> Q;
adjList.resize(n + 1);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adjList[a].push_back(b);
adjList[b].push_back(a);
}
double totalCount = 0;
for (int i = 0; i < Q; i++) {
int x, y;
cin >> x >> y;
totalCount += bfs(x, y);
}
cout << fixed << setprecision(2) << totalCount / Q << endl;
return 0;
}