A-til the Cows Come Home

Source: Internet
Author: User

Bare shortest, try to just see the SPFA, although not look at the code, but understand the general idea, first write a try it, and is a sparse map, it should be soon.

Spfa

The algorithm adopts graph storage structure as adjacency table, and the method is dynamic optimization approximation method. The algorithm sets up an advanced firstout of the queueQueueused to save vertices to be optimized, and to extract a point from this queue in order of optimizationW, and withWthe current path of the pointD[w]to optimize the path values of other pointsD[j], if there is an adjustment, thatD[j]the value is changed to a smallerwill beJPoint intoQueuequeue to continue further optimization. repeatedly fromQueuetake out points in the queue to the current shortestuntil team space does not need to be optimized,DThe shortest path from the source point to each point is saved in the array.diameter value



///////////////////////////////////////////////////////////////////////////

Once again ... It's a wonderful feeling, it's a lot easier to write.

#include <algorithm>
#include <queue>
#include <stdio.h>
#include <string.h>
#include <vector>
usingnamespaceStd

ConstintMAXN =1005;
ConstintOO =0xFFFFFFF;

structNode
{
intY, Len;
NodeintYintLen): Y (y), Len (len) {}
};
Vector<node> G[MAXN];
intV[MAXN];

voidSPFA (intS
{
queue<int> Q;

Q.push (s);

while(Q.size ())
{
s = Q.front (); Q.pop ();

intLen = G[s].size ();
for(intI=0; i<len; i++)
{
Node q = g[s][i];
if(V[s]+q.len < V[Q.Y])
{
V[Q.Y] = V[s]+q.len;
Q.push (Q.Y);
}
}
}
}

intMain ()
{
intT, N;

while(SCANF ("%d%d", &t, &n)! = EOF)
{
intI, A, B, Len;

for(i=0; i<t; i++)
{
scanf"%d%d%d", &a, &b, &len);
G[a].push_back (node (b, Len));
G[b].push_back (Node (a, Len));
}

for(i=1; i<=n; i++)
V[i] = oo;
v[1] =0;

SPFA (1);

printf"%d\n", V[n]);

for(i=1; i<=n; i++)
G[i].clear ();
}

return0;

}

A-til the Cows Come Home

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.