The question is probably test instructions: in n farms, designate a farm x, the remaining farms to have cattle to farm X to participate in the party, each cow to the farm X will take the shortest path, the return path does not necessarily follow the original way back, because each road is one-way. Return also take the shortest path. Ask N-1 cows to go to the party to return to their farm's shortest path and maximum value.
A simple shortest path, a start with the Floyd algorithm, timed out, N Max reached the complexity of 1000,n^3, absolute timeout.
Only one other algorithm can be used to solve the problem.
First, we analyze the shortest path and the problem to be solved.
The shortest path from farm X to other farms can be solved using the Dijkstra algorithm or the Bellman_ford algorithm. Represents the shortest path returned by each cow.
and the shortest path of cattle to farm x how to solve it, think of this is simple, that is, the direction of each one-way path, that is, the path from farm 1 to farm 2, into the farm 2 to farm 1 path. Then the shortest path of farm X to other farms is solved, and the shortest path of other cattle to farm X is obtained.
The following is the AC code, with detailed comments:
#include <iostream> #include <cstdio>using namespace std;const int INF = 10000000;int dis1[1005], dis2[1005]; Returns the shortest path, the last shortest path int cost[1005][1005];bool vis[1005]; Does the tag return an int N, X, M;int min (int x, int y) {return x > y? y:x;} void Dijkstra (int s, int dis[])//dijkstra algorithm solves the single source shortest path {for (int i = 0; I <= N; i++) {vis[i] = false;dis[i] = INF; }dis[s] = 0;while (true) {int v = -1;for (int u = 1; u <= N; u++)//Select a vertex with the shortest distance from the vertex that has not been selected {if (!vis[u] && (v < ; 0 | | DIS[V] > Dis[u])) v = u;} if (v = =-1) break;vis[v] = true;for (int j = 1; J <= N; j + +) {Dis[j] = min (Dis[j], dis[v] + cost[v][j]);}}} int main () {//freopen ("Data.txt", "R", stdin); int I, J, A, B, C;while (scanf ("%d%d%d", &n, &m, &x)! = EOF) {for (i = 1; I <= N; i++)//Initialize an array of each edge weight value, for (j = 1; J <= N; j + +) {if (i = = j) Cost[i][j] = 0;elsecost[i][j] = INF;} for (i = 0; i < M; i++) {scanf ("%d%d%d", &a, &b, &c); Input each edge weight value cost[a][b] = C;} Dijkstra (X, DIS1); Calculates the shortest path for (i = 1; I <= N; i++)//reverses each edge, that is, transpose the matrix {for (j = 1; j < I; J + +) {int temp = Cost[i][j];cost[i][j] = Cost[j][i];cost[j][i] = temp;}} Dijkstra (X, DIS2); Calculate departure Shortest path int max = -100000;for (i = 1; I <= N; i++)//enumeration for maximum shortest path and {if (i! = X) {int temp = Dis1[i] + dis2[i];if ( Max < temp) max = temp;}} printf ("%d\n", Max);} return 0;}
North Acm3268--silver Cow party~~ Shortest Path