Problem Description
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?
Input
The first line of each test case is two integers N (0 <= N <= 1000), M (0 <= M <= 20000). N is the number of proxy servers (labeled from 1 to N).
0 is the label of your computer and (N+1) is the label of the server of target website.
Then M lines follows, each line contains three integers u, v, w (0 <= u, v <= N + 1, 1 <= w <= 1000), means u can directly connect to v and the lag is w.
Output
If there are multiple choices, you should output the proxy server with the least label. If you can’t visit the target website by any means, output “-1” (without quotes). If you can directly visit the website and the lag is the least, output “0” (without quotes).
Example Input
43 60 1 101 2 12 4 40 3 23 2 13 4 72 40 2 100 1 51 2 42 1 71 30 2 10 1 21 2 11 30 2 100 1 21 2 1
Example Output
3-101
Hint
Author
给出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;
}