Because of the GFW (Great Firewall), we cannot directly visit many websites, such as Facebook, Twitter, YouTube, etc. But with the help of proxy and proxy server, we can easily get to these website. You have a list of several proxy servers, some of them can be connected directly but others can’t. But you can visit proxy servers through other proxy server by a one-way connection. As we all know, the lag of internet visit will decide our feelings of the visit. You have a very smart proxy software which will find the least lag way to reach the website once you choose a directly reachable proxy server. You know the lag of every connection. The lag of your visit is the all the lags in your whole connection. You want to minimize the lag of visit, which proxy server you will choose?
给出0~N+1个点,找下标最小的最短路径
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<vector> #include<set> #include<algorithm> #include<sstream> #define LL long long #define inf 0x3f3f3f3f using namespace std; const int MAXN=1010; bool visited[MAXN]; int dist[MAXN]; int w[MAXN][MAXN]; int pre[MAXN]; int main() { int T; cin>>T; while(T--) { int n,m; scanf("%d%d",&n,&m); for(int i=0;i<=n+1;i++) for(int j=0;j<=n+1;j++) if(i==j) w[i][j]=0; else w[i][j]=inf; while(m--) { int u,v,c; scanf("%d%d%d",&u,&v,&c); w[u][v]=c; } memset(dist,inf,sizeof(dist)); dist[0]=0; memset(visited,0,sizeof(visited)); pre[0]=-1; for(int i=0;i<=n+1;i++) { int minx=inf,pos; for(int j=0;j<=n+1;j++) if(!visited[j]&&dist[j]<=minx) { minx=dist[j]; pos=j; } visited[pos]=1; for(int j=0;j<=n+1;j++) if(!visited[j]&&dist[j]>=dist[pos]+w[pos][j])//每次松弛的时候找最小的标号 { if(dist[j]==dist[pos]+w[pos][j]) { pre[j]=min(pre[j],pos); } else { dist[j]=dist[pos]+w[pos][j]; pre[j]=pos; } } } if(dist[n+1]==inf) cout<<-1<<endl; else { if(pre[n+1]==0) cout<<0<<endl; else { int k=n+1; while(pre[k]!=-1) { if(pre[k]==0) break; k=pre[k]; } cout<<k<<endl; } } } return 0; }