Java求解股票经纪人KK想要在一群人(n个人的编号为0~n-1)中散布一个传言,传言只通过认识的人进行传递,在两个认识的人之间传递消息所需要的时间各有不同,在一群人中,KK想要找出以哪个人为起点开始传递这个传言,可以在耗时最短的情况下认所有人都收到消息。
时间: 2024-01-22 19:19:20 浏览: 32
这个问题可以使用 Floyd-Warshall 算法求解。具体思路如下:
1. 构建一个邻接矩阵 graph,表示人与人之间的边和边的权值。
2. 使用 Floyd-Warshall 算法计算任意两点之间的最短路径。
3. 对于每个人 i,计算以他为起点传递消息所需要的时间,即从 i 出发到其他所有人的最短路径中的最大值。
4. 找出所有人中,以哪个人为起点传递消息所需时间最短,即可得到答案。
下面是 Java 代码实现:
```java
public class RumorSpread {
public static int findStartPerson(int[][] graph) {
int n = graph.length;
int[][] dist = new int[n][n];
int maxDist = Integer.MAX_VALUE;
int startPerson = -1;
// 初始化邻接矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
dist[i][j] = 0;
} else if (graph[i][j] > 0) {
dist[i][j] = graph[i][j];
} else {
dist[i][j] = maxDist;
}
}
}
// Floyd-Warshall 算法求任意两点之间的最短路径
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][k] != maxDist && dist[k][j] != maxDist && dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
// 计算以每个人为起点传递消息所需时间
for (int i = 0; i < n; i++) {
int maxTime = 0;
for (int j = 0; j < n; j++) {
if (dist[i][j] > maxTime) {
maxTime = dist[i][j];
}
}
if (maxTime < maxDist && maxTime < startPerson || startPerson == -1) {
startPerson = i;
}
}
return startPerson;
}
public static void main(String[] args) {
int[][] graph = {{0, 2, 4, 5},
{2, 0, 1, 4},
{4, 1, 0, 1},
{5, 4, 1, 0}};
int startPerson = findStartPerson(graph);
System.out.println("Start person: " + startPerson);
}
}
```
在上面的代码中,我使用了一个变量 maxDist 表示无穷大,即表示两个人之间没有边相连。如果两个人之间有边相连,则将其权值赋给对应的 dist[i][j]。在计算任意两点之间的最短路径时,如果 dist[i][k] 和 dist[k][j] 的值不为无穷大且它们的和小于 dist[i][j],则更新 dist[i][j]。
在计算以每个人为起点传递消息所需时间时,我先将 maxTime 初始化为 0,然后找到从 i 出发到其他所有人的最短路径中的最大值。如果这个最大值比当前的 startPerson 更小,则更新 startPerson。最后返回 startPerson 即可。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)