poj1511_spfa
题意:长篇大论就是构建正反两个图,然后将正反图中各点距离源点的最短距离相加。
分析:spfa和邻接表,注意答案得用long long 存啊。
代码:
View Code
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <queue> 5 using namespace std; 6 //spfa 7 //58924K 1625MS 8 const int maxnum=1000005; 9 const int maxdigit=1000000000; 10 struct edge 11 { 12 int v; 13 int w; 14 int next; 15 }edge[maxnum],Edge[maxnum]; 16 typedef struct 17 { 18 bool use; 19 long long d; 20 int pre; 21 }pp; 22 pp point[maxnum]; 23 typedef struct 24 { 25 bool use; 26 int d; 27 int pre; 28 }ppp; 29 ppp ppoint[maxnum]; 30 int p,e; 31 long long ans; 32 queue<int> q; 33 34 void spfa(int u) 35 { 36 point[u].d=0; 37 point[u].use=true; 38 q.push(u); 39 int t,i; 40 while(!q.empty()) 41 { 42 t=q.front(); 43 q.pop(); 44 point[t].use=false; 45 for(i=point[t].pre;i!=-1;i=edge[i].next) 46 { 47 int v=edge[i].v; 48 int w=edge[i].w; 49 if(point[v].d>point[t].d+w) 50 { 51 point[v].d=point[t].d+w; 52 if(!point[v].use) 53 { 54 point[v].use=true; 55 q.push(v); 56 } 57 } 58 } 59 } 60 for(i=2;i<=p;i++) 61 ans+=point[i].d; 62 } 63 64 void Spfa(int u) 65 { 66 ppoint[u].d=0; 67 ppoint[u].use=true; 68 q.push(u); 69 int t,i; 70 while(!q.empty()) 71 { 72 t=q.front(); 73 q.pop(); 74 ppoint[t].use=false; 75 for(i=ppoint[t].pre;i!=-1;i=Edge[i].next) 76 { 77 int v=Edge[i].v; 78 int w=Edge[i].w; 79 if(ppoint[v].d>ppoint[t].d+w) 80 { 81 ppoint[v].d=ppoint[t].d+w; 82 if(!ppoint[v].use) 83 { 84 ppoint[v].use=true; 85 q.push(v); 86 } 87 } 88 } 89 } 90 for(i=2;i<=p;i++) 91 ans+=ppoint[i].d; 92 } 93 int main() 94 { 95 int num,i; 96 scanf("%d",&num); 97 while(num--) 98 { 99 ans=0; 100 scanf("%d%d",&p,&e); 101 for(i=1;i<=p;i++) 102 { 103 point[i].d=maxdigit; 104 point[i].use=false; 105 point[i].pre=-1; 106 ppoint[i].d=maxdigit; 107 ppoint[i].use=false; 108 ppoint[i].pre=-1; 109 } 110 int u,v,w; 111 for(i=1;i<=e;i++) 112 { 113 scanf("%d%d%d",&u,&v,&w); 114 edge[i].v=v; 115 edge[i].w=w; 116 edge[i].next=point[u].pre; 117 point[u].pre=i; 118 Edge[i].v=u; 119 Edge[i].w=w; 120 Edge[i].next=ppoint[v].pre; 121 ppoint[v].pre=i; 122 } 123 spfa(1); 124 Spfa(1); 125 printf("%I64d\n",ans); 126 } 127 return 0; 128 } 129 130 /* 131 2 132 2 2 133 1 2 13 134 2 1 33 135 4 6 136 1 2 10 137 2 1 60 138 1 3 20 139 3 4 10 140 2 4 5 141 4 1 50 142 */
tjuoj 2217