HDU 2680 Choose the best route (SPFA algorithm)

Source: Internet
Author: User

Link: Click to open link

The main idea:

Enter N,m,s, which represents n points, m edges, and s represents the end point. Then input the side, each side input p,q,t;p,q represents two points, T is the edge right, notice that the topic is from P point to Q side, it should establish a directed graph. Then enter W to indicate that there is a W starting point, and then enter the starting point, and for multiple starting points, if you use a SPFA for each starting point, then the starting point can be a bit cumbersome, so you might want to do this: In addition to a point that does not coincide with the topic, set the Benquan of all the starting point to 0, Then finding the point as the starting point is the shortest. Please refer to the code for details:

#include <stdio.h> #include <string.h> #include <queue> #define MAXN 1010#define MAXM 40040#define INF 0x3f3f3f3fusing namespace Std;int head[maxn];int dis[maxn];int mark[maxn];struct node{int from,to,val,next;}; Node Edge[maxm];int num,n,m,s;void getmap (int u,int v,int W) {node e={u,v,w,head[u]};edge[num]=e;head[u]=num++;} void SPFA (int s) {Queue<int>q;memset (mark,0,sizeof (Mark)); memset (dis,inf,sizeof (dis)); Q.push (s); mark[s]=1; Dis[s]=0;while (!q.empty ()) {int Top=q.front (); Q.pop (); mark[top]=0;for (int i=head[top];i!=-1;i=edge[i].next) {int u= Edge[i].to;if (dis[u]>dis[top]+edge[i].val) {dis[u]=dis[top]+edge[i].val;if (!mark[u]) {mark[u]=1;q.push (U);}}}} int main () {while (scanf ("%d%d%d", &n,&m,&s)!=eof) {memset (head,-1,sizeof (head)); num=0;for (int i=0;i< m;i++) {int a,b,d;scanf ("%d%d%d", &a,&b,&d); Getmap (a,b,d);} int w,start;scanf ("%d", &w), for (int i=0;i<w;i++) {scanf ("%d", &start); Getmap (0,start,0);} SPFA (0); if (dis[s]==inf) printf (" -1\n"); elseprintf ("%D\n ", Dis[s]);} return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

HDU 2680 Choose the best route (SPFA algorithm)

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.