题目链接:点我啊╭(╯^╰)╮
题目大意:
奶牛派对:有分别来自 N 个农场的 N 头牛去农场 X 嗨皮,农场间由 M 条有向路径连接。每头牛来回都挑最短的路走,求它们走的路的最大长度?
解题思路:
回来的路就是第一遍Dijkstra,去的路就是把图反过来跑一遍Dijkstra…
代码思路:
转置矩阵
#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3F3F3F3F;
const int N = 1005;
int m, n, st, mp[N][N], t, maxx;
int dis[N], vis[N], ans[N], vis2[N][N];
void init() {
for (int i=1; i<=n; i++) {
for (int j=1; j<=n; j++) {
if (i == j) mp[i][j] = 0;
else mp[i][j] = INF;
}
dis[i]=INF;
}
memset(vis, 0, sizeof(vis));
}
void creatgraph() {
int t1, t2, t3;
for (int i=0; i<m; i++) {
scanf("%d%d%d", &t1, &t2, &t3);//两个顶点和权值
if (mp[t1][t2] > t3)//防止重复输入相同节点,但是权值不同
mp[t1][t2] = t3;
//mp[t2][t1] = t3;
}
}
void dijkstra(int st) {
for (int i=1; i<=n; i++)
dis[i] = mp[st][i];
vis[st] = 1;
for (int i=1; i<=n-1; i++) { //循环n-1次
/*找出离起点最近的点*/
int minn = INF, k = -1;
for (int j=1; j<=n; j++) {
if (!vis[j] && dis[j]<minn) {
minn = dis[j];
k = j;
}
}
if(k==-1) break;
vis[k] = 1;
for (int j=1; j<=n; j++) { //松弛操作,找到媒介使得出现新的最短路
if (!vis[j] && dis[k]+mp[k][j] < dis[j])
dis[j] = dis[k] + mp[k][j];
}
}
if(t) for (int i=1; i<=n; i++) maxx = max(maxx, ans[i]+dis[i]);
else for (int i=1; i<=n; i++) ans[i] = dis[i];
}
int main() {
scanf("%d%d%d", &n, &m, &st); //n个顶点,m条边
init(); //初始化地图
creatgraph(); //建图
dijkstra(st);
for (int i=1; i<=n; i++)
for (int j=i+1; j<=n; j++)
swap(mp[j][i], mp[i][j]);
t++;
memset(vis, 0, sizeof(vis));
dijkstra(st);
printf("%d", maxx);
}