Dijkstra O (n2) algorithm Template

Source: Internet
Author: User
# Include <iostream> # include <memory> using namespace STD; const int maxint = 9999999; const int maxn = 1010; int data [maxn] [maxn], lowcost [maxn]; // The distance between data storage points, the distance from lowcost storage point to start, and the bool used [maxn] is stored from 0; // whether the mark point is selected int N; // Number of vertices void dijsktra (INT start) // The initial vertex is the Dijkstra algorithm of start {int I, j; memset (used, 0, sizeof (used )); // initially, all vertices are not marked as for (I = 0; I <n; I ++) lowcost [I] = data [start] [I]; // The distance from the initial point to all other points used [Start] = true; // The initial vertex is marked as lowcost [start] = 0; // The initial vertex is always 0, and the shortest path is for (I = 0; I <n-1; I ++) // because the first point start has been selected, all the other n-1 points are left {// choose min select a point int tempmin = maxint; int choose; for (j = 0; j <n; j ++) // a round of loop indicates selecting a point {If (! Used [J] & tempmin> lowcost [J]) // dynamically update similar to max value {choose = J; tempmin = lowcost [J];} used [Choose] = true; // The selected vertex is marked with a choose vertex. // updata others updates lowcost [] for (j = 0; j <N; j ++) {If (! Used [J] & Data [Choose] [J] <maxint & lowcost [Choose] + data [Choose] [J] <lowcost [J]) /* Find the point from choose to another unselected distance <maxint indicates the distance between the existing & start point and choose + the distance from the choose point to this point <start point to this point */ lowcost [J] = lowcost [Choose] + data [Choose] [J]; // update the array if the above if condition is met }}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.