1. 程式人生 > >1072 Gas Station (30 分)(最短路徑)

1072 Gas Station (30 分)(最短路徑)

 

#include<bits/stdc++.h>

using namespace std;
const int N=1e3+100;
int n,m,k,Ds;
int mp[N][N];
int dis[N];
int vis[N];
int inf=0x3f3f3f3f;
int toint(char s[])
{
    int sum=0;
    int len=strlen(s);
    for(int i=0;i<len;i++){
        if(s[i]=='G') continue;
        sum=sum*10+s[i]-'0'
; } if(s[0]=='G') return sum+n; return sum; } void Dijkstra(int v) { fill(vis,vis+N,false); fill(dis,dis+N,inf); for(int i=1;i<=n+m;i++){ dis[i]=mp[v][i]; } dis[v]=0; for(int i=0;i<n+m;i++){ int u=-1; int minn=inf; for(int j=1;j<=n+m;j++){
if(!vis[j]&&minn>dis[j]){ u=j; minn=dis[j]; } } vis[u]=true; for(int j=1;j<=n+m;j++){ if(!vis[j]&&dis[j]>mp[u][j]+dis[u]){ dis[j]=mp[u][j]+dis[u]; } } } }
int main() { scanf("%d %d %d %d",&n,&m,&k,&Ds); fill(mp[0],mp[0]+N*N,inf); for(int i=0;i<k;i++){ char s1[5],s2[5]; int num; scanf("%s %s %d",s1,s2,&num); int a=toint(s1); int b=toint(s2); mp[a][b]=mp[b][a]=num; } int id=-1; double maxDis=-1; double minAvg=inf; for(int i=n+1;i<=n+m;i++){ Dijkstra(i); double avg=0; double Min=inf; bool flag=false; for(int j=1;j<=n;j++){ if(dis[j]>Ds){ flag=true; break; } if(Min>dis[j]){ Min=dis[j]; } avg+=1.0*dis[j]/n; } if(flag) continue; if(maxDis<Min){ maxDis=Min; id=i; minAvg=avg; } else if(maxDis==Min&&minAvg>avg){ id=i; minAvg=avg; } } if(id==-1) printf("No Solution\n"); else{ printf("G%d\n",id-n); printf("%.1f %.1f\n",maxDis,minAvg); } return 0; }