【题目链接】
T组数据
每组n个点m条边,给一个有向图,边有长度。
接下来Q个询问
每次问u到v至少经过x个点的最短距离
The first line of the input contains an integer T(1≤T≤10), denoting the number of test cases.
In each test case, there are 2 integers n,m(2≤n≤50,1≤m≤10000) in the first line, denoting the number of intersections and one way streets.
In the next m lines, each line contains 3 integers ui,vi,wi(1≤ui,vi≤n,ui≠vi,1≤wi≤10000), denoting a one way street from the intersection ui to vi, and the length of it is wi.
Then in the next line, there is an integer q(1≤q≤100000), denoting the number of days.
In the next q lines, each line contains 3 integers si,ti,ki(1≤si,ti≤n,1≤ki≤10000), describing the walking plan.
For each walking plan, print a single line containing an integer, denoting the minimum total walking length. If there is no solution, please print -1.
Sample Input
2
3 3
1 2 1
2 3 10
3 1 100
3
1 1 1
1 2 1
1 3 1
2 1
1 2 1
1
2 1 1
Sample Output
111
1
11
-1
题目中要求至少经过的点的数量不超过10000,所以分成100*100做。
dpa[t][i][j]表示从i到j恰好经过t个点的最短路径,t<=100;
dpb[t][i][j]表示从i到j恰好经过t*100个点的最短路径,t<=100;
dpc[t][i][j]表示从i到j至少经过t个点的最短距离,t<=100;
dis[i][j]表示从i到j的最短路;//floyed预处理
#include
#define LL long long
using namespace std;
const int maxn = 57;
const int maxt = 107;
const LL mod = 1e18+7;
const LL INF=1e15;
LL dpa[maxt][maxn][maxn];
LL dpb[maxt][maxn][maxn];
LL dpc[maxt][maxn][maxn];
LL edge[maxn][maxn];
LL dis[maxn][maxn];
int main()
{
LL T,n,m,i,j,k,x,y,u,v,Q,t,ans;
ios::sync_with_stdio(false);
cin>>T;
while(T--)
{
cin>>n>>m;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
edge[i][j]=INF;
if(i!=j) dis[i][j]=INF;
}
while(m--)
{
cin>>u>>v>>x;
edge[u][v]=min(edge[u][v],x);
dis[u][v]=edge[u][v];
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i!=j) {dpa[0][i][j]=dpb[0][i][j]=
dpc[0][i][j]=INF;}
}
}
for(t=1;t<=100;t++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dpa[t][i][j]=INF;
for(k=1;k<=n;k++)
{
dpa[t][i][j]=min(dpa[t][i][j],dpa[t-1][i][k]+edge[k][j]);
}
}
}
}
for(t=1;t<=100;t++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dpb[t][i][j]=INF;
for(k=1;k<=n;k++)
{
dpb[t][i][j]=min(dpb[t][i][j],dpb[t-1][i][k]+dpa[100][k][j]);
}
}
}
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
for(k=1;k<=n;k++)
dis[j][k]=min(dis[j][k],dis[j][i]+dis[i][k]);
for(t=0;t<=100;t++)///注意这里是从0开始
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
dpc[t][i][j]=dpa[t][i][j];
for(k=1;k<=n;k++)
{
dpc[t][i][j]=min(dpc[t][i][j],dpa[t][i][k]+dis[k][j]);
}
}
}
}
cin>>Q;
while(Q--)
{
cin>>u>>v>>x;
ans=INF;
for(i=1;i<=n;i++)
{
ans=min(ans,dpb[x/100][u][i]+dpc[x%100][i][v]);
}
if(ans
else cout<<"-1\n";
}
}
return 0;
}