Home > Back-end >  A greedy algorithm to achieve the shortest path
A greedy algorithm to achieve the shortest path

Time:11-23

Greedy algorithm is
% has been, longitude coordinates X, Y dimension coordinates, the distance matrix DG (distance root of square sum for the latitude and longitude)
N=30; % here is known to have 30 points
X=x; After % produces a points the same row vector
Y=y;
D=DG.
% distance matrixBest=1: n. % to generate a matrix used to save point order
Handle=1: n.
Best (1)=1; % the default starting point
Num=1;
For a=1: (n - 2) % n - 2 times judgment
Handle (:, 1)=[]; % last the most advantage of the data redundant
Dis=zeros (1) (n - a); % is used to save the rest each point distance
For b=% 1: (n - a) used to retrieve the remaining distance of each point
Dis (b)=d (num, handle (b));
End
Num1=find (dis==min (dis)); Get the advantage in retrieval
%
T=handle (1); % will be the most advantages and point location in front of swapping
The handle (1)=handle (num1);
Handle (num1)=t;

Num=handle (1); Manipulation, % to get the next number
Best (a + 1)=handle (1); % will be the most advantage in the best array
End

The best (n)=handle (num1); % catch up on the last point
X (best)
Y (best)
Plot (x (best), y (best), the '+'); Marked with a '+' % point is connected by solid lines to get the optimal path
The grid on

% to get the order, in front of the dimensions of the output for the ans
[ians, iY]=find (bsxfun (@ eq, ans, Y ')); % compare get displacement order
W=accumarray (iY, 1: numel (iY), [], @ (x) {ians (x)});
Celldisp (w)

CodePudding user response:

 
#include
#include
#include
#include
#include
using namespace std;
Const int N=100001;
Const int inf=0 x3f3f3f3f;
Struct node {
Int, v, w;
The node () {

}
The node (int vv, int ww) {
V=vv;
W=ww;
}
};
vector G [N];
Int n, m, s;
Int d [N].
Set Min_heap;
Int main () {
Cin & gt;> N & gt;> M & gt;> s;
for (int i=0; I & lt; m; I++) {
Int, u, v, w;
Cin & gt;> U & gt;> V & gt;> w;
G [u] push_back (node (v, w));
G [v] push_back (node (u, w));
}
Memset (d, 0 x3f, sizeof (d));
D [s]=0;
Min_heap. Insert (make_pair (0, s));
While (min_heap. The size ()) {
Int mind=min_heap. The begin () - & gt; First;
Int v=min_heap. The begin () - & gt; Second;
Min_heap. Erase (min_heap. The begin ());
for (int i=0; iIf (d/g [v] [I] v] & gt; D + g [v] [v] [I]. W) {
Min_heap. Erase (make_pair (d/g [v] [I] v], g [v] [I] v));
[d] g [v] [I]. V=d [v] + g [v] [I]. W.
Min_heap. Insert (make_pair (d/g [v] [I] v], g [v] [I] v));
}
}
}
for (int i=1; I & lt;=n; I++) {
Cout & lt; }
return 0;
}
  • Related