题意:先给你一张你n * n的图,代表城市间的距离,然后,给出n个tax的费用,然后很多询问,问你a到b的最少费用,并且打印路径(字典序)
注意tax的费用起点和终点不算
逆序spfa:
#include<iostream> #include<deque> #include<vector> #include<algorithm> #include<list> #include<cstdio> using namespace std; const int maxn=1<<7; const int inf=0x7fffffff; int a[maxn][maxn]; int b[maxn]; int d[maxn]; bool vis[maxn]; int pre[maxn]; int N,x,y,temp; int out[maxn]; deque<int>q; inline void init() { for(int i=1; i<=N; i++) { d[i]=inf; pre[i]=inf; vis[i]=false; } d[y]=0; q.clear(); return ; } void spfa() { q.push_front(y); vis[y]=true; while(!q.empty()) { temp=q.back(); q.pop_back(); for(int i=1; i<=N; i++) { if(-1 == a[i][temp] || i==temp) { continue; } else { if( d[temp] + b[i] + a[i][temp] < d[i] ) { d[i]=d[temp] + b[i] + a[i][temp]; pre[i]=temp; if(vis[i]==false) { q.push_front(i); vis[i]=true; } } else if( d[temp] + b[i] + a[i][temp] == d[i] ) { if(temp < pre[i]) { pre[i]=temp; } } } } vis[temp]=false; } out[0]=x; temp=0; while( pre[out[temp]] != inf ) { out[temp+1]=pre[out[temp]]; temp++; } printf("From %d to %d :\nPath: ",x,y); for(int i=0; i<temp; i++) { printf("%d-->",out[i]); } printf("%d\n",out[temp]); printf("Total cost : %d\n\n",d[x]-b[x]); return ; } int main() { while(cin>>N && N) { for(int i=1; i<=N; i++) { for(int j=1; j<=N; j++) { cin>>a[i][j]; } } for(int i=1; i<=N; i++) { cin>>b[i]; } while(cin>>x>>y) { if(-1==x && -1==y) { break; } if(x!=y) { init(); spfa(); } else { printf("From %d to %d :\n",x,y); printf("Path: %d\n",x); printf("Total cost : 0\n\n"); } } } return 0; }
时间: 2024-10-16 05:08:51