1. 程式人生 > >Warfare And Logistics UVA - 1416

Warfare And Logistics UVA - 1416

logs int 時間復雜度 一個 spfa logistic first 最短 fine

題目鏈接:https://vjudge.net/problem/UVA-1416

題解:

  這是一個最短路的好題,首先我們考慮如果暴力弗洛伊德,顯然時間復雜度不對,如果做n次spfa好像復雜度也不對,所以考慮優化這個暴力。

  我們考慮對於一個單源最短路,只有改變了最短路樹中的某條邊,才需要重新做一次最短路。所以我們不需要對於每條邊都重新做最短路,只需要對於在最短路數上的邊做,所以時間復雜度就優化成了你】

mn^2log(n)。

  實現的時候要用pre數組記下,以i為終點的最短路樹的邊,實現有點復雜,看一下代碼吧。

代碼:

#include <cstdio>
#include 
<iostream> #include <algorithm> #include <cstring> #include <cmath> #include <iostream> #include <queue> #define MAXN 10000 #define ll long long using namespace std; struct edge{ int first,next,to,quan,id; }a[MAXN*2]; struct heapnode{ int id,x; bool operator
< (const heapnode &h)const{ return h.x<x; } }; priority_queue<heapnode> q; int dis[MAXN],have[MAXN],hh[MAXN],pre[MAXN],n,m,l,inf,num=0; ll t[MAXN]; void addedge(int from,int to,int quan,int id){ a[++num].to=to; a[num].id=id; a[num].quan=quan; a[num].next=a[from
].first; a[from].first=num; } ll dij(int s,int cant){ memset(dis,127,sizeof(dis));inf=dis[0]; memset(have,0,sizeof(have)); memset(pre,0,sizeof(pre)); while(!q.empty()) q.pop(); dis[s]=0;q.push((heapnode){s,0}); while(!q.empty()){ int now=q.top().id; q.pop(); if(have[now]) continue; have[now]=1; for(int i=a[now].first;i;i=a[i].next){ int to=a[i].to,quan=a[i].quan,id=a[i].id; if(id==cant) continue; if(dis[to]>dis[now]+quan){ pre[to]=id; dis[to]=dis[now]+quan; q.push((heapnode){to,dis[to]}); } } } ll ret=0; for(int i=1;i<=n;i++){ if(dis[i]==inf) ret+=l; else ret+=dis[i]; } return ret; } void sovle(int s){ int c=dij(s,0); for(int i=1;i<=n;i++) hh[i]=pre[i]; for(int i=0;i<=m;i++) t[i]+=c; for(int i=1;i<=n;i++) if(hh[i]) t[hh[i]]+=dij(s,hh[i])-c; } int main() { while(scanf("%d%d%d",&n,&m,&l)!=EOF){ memset(a,0,sizeof(a)); memset(t,0,sizeof(t)); num=0; for(int i=1;i<=m;i++){ int x,y,z;scanf("%d%d%d",&x,&y,&z); addedge(x,y,z,i),addedge(y,x,z,i); } for(int i=1;i<=n;i++) sovle(i); ll ans=0; for(int i=1;i<=m;i++) ans=max(ans,t[i]); printf("%lld %lld\n",t[0],ans); } return 0; }

Warfare And Logistics UVA - 1416