uva10986-sending Email (Dijkstra)
Topic links
The main topic: to n points, M edge, there is a starting point and end point, ask the shortest distance from the beginning to the end, not up to unreachable.
Problem-solving ideas: The shortest path, Dijkstra algorithm.
Code:
#include <cstdio>#include <queue>#include <vector>#include <string.h>using namespace STD;usingStd::make_pair;typedefpair<int,int> Pii;priority_queue<pii, vector<pii>, Greater<pii> >q;Const intINF =0x3f3f3f3f;Const intMAXN =2e4;Const intMAXM =1e5+5;intFIRST[MAXN];intU[MAXM], V[MAXM], W[MAXM], NEXT[MAXM];intD[MAXN]; void read_graph (int n, int m) { for(inti =0; I < n; i++) First[i] =-1; M *=2; for(inti =0; I < m; i++) {scanf("%d%d%d", &u[i], &v[i], &w[i]); Next[i] = first[u[i]]; First[u[i]] = i; i++; U[i] = v[i-1]; V[i] = u[i-1]; W[i] = w[i-1]; Next[i] = first[u[i]]; First[u[i]] = i; }} int Dijkstra (int s, int t, int n) { for(inti =0; I < n; i++) D[i] = (i = = s)?0: INF; Q.push (Make_pair (d[s],s)); PII cur; while(!q.empty ()) {cur = q.top (); Q.pop ();if(Cur.first! = D[cur.second])Continue; for(inti = First[cur.second]; I! =-1; i = Next[i])if(D[v[i]] > D[u[i]] + w[i]) {D[v[i]] = D[u[i]] + w[i]; Q.push (Make_pair (D[v[i]), v[i]); } }returnD[T];} int main () {intTscanf("%d", &t);intN, M, s, t, CAS =0; while(t--) {scanf("%d%d%d%d", &n, &m, &s, &t); Read_graph (n, m);intAns = Dijkstra (s, t, N);if(ans = = INF)printf("Case #%d:unreachable\n", ++cas); Elseprintf ("Case #%d:%d\n", ++cas, ans) ; }return 0;}
uva10986-sending Email (Dijkstra)