link : Click here
Test instructions
The general South commanded N troops, which were stationed in n different cities. He is using these N troops to maintain the law and order of M cities, the M cities numbered from 1 to M respectively. Now, the handyman advisers told the south General, the city of K riots, South General from all the troops sent a unit along the nearest road to the riot city of insurgency. Now that you know the time required to march between any of the two cities, you, as the most powerful programmer in the South, ask you to write a program to tell the first squad of the Southern general how long it will take to reach the rebel city.
idea : The shortest Path problem entry: Out of the data comparison of water, see others are using priority queue Dijkstra implementation, efficiency improved a lot. The shortest short-circuit problem exercise too little, this question still give a little confidence, first of all.
Reference code:
#include <string.h> #include <stdio.h> #include <iostream> #include <algorithm>using namespace std;const int Inf=0x3f3f3f3f;const int maxn=1010;int COST[MAXN][MAXN]; Save diagram int D[MAXN]; The shortest path starting from S bool USED[MAXN]; An already used figure int V; Vertex number int city[maxn];void Dijkstra (int s) {for (int i=0; i<v; i++) d[i]=cost[s][i]; memset (used,false,sizeof (used)); d[s]=0; The self-weight value is 0 used[s]=true; while (true) {int v=-1; for (int u=0; u<v; u++) {if (!used[u]&& (v==-1| | D[U]<D[V]) V=u; } if (v==-1) break; Used[v]=true; for (int u=0; u<v; u++) d[u]=min (D[u],d[v]+cost[v][u]); }//return d[v];} int main () {int ncase,n,p,q,i,j; scanf ("%d", &ncase); while (ncase--) {int U,v,quan; memset (cost,inf,sizeof (cost)); scanf ("%d%d%d%d", &n,&v,&p,&q); for (i=0; i<n; i++) scanf ("%d", &city[i]); for (i=0; i<p; i++) {scanf ("%d%d%d", &u,&v,&quan); if (Cost[u][v]>quan) Cost[u][v]=cost[v][u]=quan; } int temp=inf; Dijkstra (Q); for (i=0; i<n; i++) {if (Temp>d[city[i]]) temp=d[city[i]]; } printf ("%d\n", temp); } return 0;}
Nyoj 115 City Insurgency (Dijkstra introduction)