The dijkstral algorithm of Usaco--3.2sweet butter+ push optimization

Source: Internet
Author: User
Tags stdin

The idea of this topic is very simple, we just need to enumerate each vertex as the destination, and then take the sum of the minimum distance as the answer. At first I used Floyd to find out the minimum distance between all points at once, but it timed out.
The next time you enumerate a point, use the heap-optimized dijkstral to find the shortest path to the rest of the point, so it's too late. The adjacency matrix of the graph is also simulated with an array in the algorithm.

The code is as follows:

/*id:15674811lang:c++task:butter*/#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace STD;#define MAXN 810#define INF 0x3f3f3f3fintP[MAXN],D[MAXN],FIRST[MAXN],VIS[MAXN];intu[maxn*Ten],v[maxn*Ten],w[maxn*Ten],next[maxn*Ten];intE,n,k,m;;voidAdd_e (intXintYintz) {u[e]=x; v[e]=y; w[e]=z;       NEXT[E]=FIRST[X]; first[x]=e++;}typedefpair<int,int&GT;PII;PRIORITY_QUEUE&LT;PII, vector<pii>,greater<pii> >q;voidDijkstral (intx) {memset(Vis,0,sizeof(VIS));memset(d,0x3f,sizeof(d)); d[x]=0; Q.push (Make_pair (d[x],x)); while(!q.empty ()) {PII u=q.top (); Q.pop ();intX=u.second;if(Vis[x])Continue; vis[x]=1; for(intk=first[x];k!=-1; K=next[k])if(D[v[k]]>d[x]+w[k])                      {D[v[k]]=d[x]+w[k];                 Q.push (Make_pair (d[v[k]],v[k)); }      }}intMain () {Freopen ("Butter.in","R", stdin); Freopen ("Butter.out","W", stdout);//freopen ("In.txt", "R", stdin);       intSum=inf;scanf("%d%d%d", &k,&n,&m); for(intI=0; i<k;i++)scanf("%d", &p[i]); E=0; for(intI=1; i<=n;i++) first[i]=-1; for(intI=1; i<=m;i++) {intX, Y, Zscanf("%d%d%d", &x,&y,&z);             Add_e (x, y, z);      Add_e (Y,X,Z); } for(intI=1; i<=n;i++) {dijkstral (i);inttmp=0, J; for(j=0; j<k;j++) {if(D[p[j]]>=inf) Break;            TMP+=D[P[J]]; }if(j>=k&&sum>tmp) sum=tmp; }printf("%d\n", sum);return 0;}

The dijkstral algorithm of Usaco--3.2sweet butter+ push optimization

Related Article

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.