标签:
6 7 1 2 3 4 5 6 1 2 1 2 3 2 3 4 3 4 5 4 1 5 5 2 5 2 1 4 3 5 1 4 2 3 1 5 3 5 1 6 2 1 10 20 1 2 5 1 1 2 0 0
7 5 8 9 -1 25
1 #include <cstdio> 2 #include <queue> 3 #include <iostream> 4 #include <cstring> 5 #define pil pair<LL,int> 6 using namespace std; 7 typedef long long LL; 8 const LL INF = 0x3f3f3f3f3f3f3f3f; 9 const int maxn = 2010; 10 int head[maxn],tot,n,m,q,p[maxn],from[maxn*100],to[maxn*100]; 11 bool done[maxn]; 12 LL d[maxn],ans[maxn*100]; 13 struct arc { 14 int to,w,next; 15 arc(int x = 0,int y = 0,int z = -1) { 16 to = x; 17 w = y; 18 next = z; 19 } 20 } e[100010]; 21 void add(int u,int v,int w) { 22 e[tot] = arc(v,w,head[u]); 23 head[u] = tot++; 24 } 25 priority_queue<pil,vector<pil >,greater<pil > >qq; 26 void dijkstra(int s){ 27 while(!qq.empty()) qq.pop(); 28 for(int i = 1; i <= n; ++i){ 29 d[i] = INF; 30 done[i] = false; 31 } 32 d[s] = 0; 33 qq.push(pil(0,s)); 34 while(!qq.empty()){ 35 int u = qq.top().second; 36 qq.pop(); 37 if(done[u]) continue; 38 done[u] = true; 39 for(int i = head[u]; ~i; i = e[i].next){ 40 if(p[e[i].to] <= p[s] && !done[e[i].to] && d[e[i].to] > d[u] + e[i].w){ 41 d[e[i].to] = d[u] + e[i].w; 42 qq.push(pil(d[e[i].to],e[i].to)); 43 } 44 } 45 } 46 for(int i = 0; i < q; ++i) 47 if(d[from[i]] < INF && d[to[i]] < INF) 48 ans[i] = min(ans[i],d[from[i]] + d[to[i]] + p[s]); 49 } 50 int main() { 51 int u,v,w; 52 while(scanf("%d%d",&n,&m),n||m) { 53 for(int i = 1; i <= n; ++i) 54 scanf("%d",p+i); 55 memset(head,-1,sizeof head); 56 tot = 0; 57 while(m--){ 58 scanf("%d%d%d",&u,&v,&w); 59 add(u,v,w); 60 add(v,u,w); 61 } 62 scanf("%d",&q); 63 for(int i = 0; i < q; ++i){ 64 scanf("%d%d",from+i,to+i); 65 ans[i] = INF; 66 } 67 for(int i = 1; i <= n; ++i) dijkstra(i); 68 for(int i = 0; i < q; ++i) 69 printf("%I64d\n",ans[i] == INF?-1:ans[i]); 70 puts(""); 71 } 72 return 0; 73 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4785332.html